1
1

More than 1 year has passed since last update.

addSubviewしたカスタムビューのUIButtonが押せない時

Last updated at Posted at 2022-07-08

はじめに

xibでカスタムビューを作成し、viewControllerでaddSubviewしたのですが、カスタムビュー内のUIButtonをタップしても反応してくれなかったので対処法をメモ

原因

カスタムビューのサイズ指定をviewControllerではなくカスタムビューで行っていました。

CustomView.swift
final class CustomView: UIView { 

  @IBOutlet private weak var button: UIButton!
  
  init() {
    let view = UINib(nibName: "UpperSearchView", bundle: nil).instantiate(withOwner: self, options: nil).first as! UIView
    view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 50) //カスタムビューでサイズ指定
    addSubview(view)
  }
}

対処法

カスタムビューのサイズ指定をviewControllerでaddSubviewした後に行います。

ViewController.swift
final class ViewController: UIViewController {

  @IBOutlet private weak var containerView: UIView!
  private let customView = CustomView()

  override func viewDidLoad() {
    super.viewDidLoad()
    containerView.addSubview(customView)
    customView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 50) //viewControllerでサイズ指定
  }
}

さいごに

他にもviewControllerにタップされた時のメソッドを追加し、addTargetすることでも可能ですが、今回は一番手っ取り早い方法で対応しました。
以上です。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1