はじめに
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することでも可能ですが、今回は一番手っ取り早い方法で対応しました。
以上です。