こんばんは sohnishi です。
なんかUINavigationBarのサイズ感がおかしくなってるような気がするこの頃です。
タップ領域をinsetsの設定だけで変更できなくなっていました。。。
なので、UITapGestureRecognizerで対応してみたいと思います。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import UIKit class HogeViewController: UIViewController { var hogeBtn = UIButton() var hogeBarButtonItem = UIBarButtonItem() var navBarTapGestureRecognizer: UITapGestureRecognizer! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navBarTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.navBarTapGesture(gestureRecognizer:))) self.navigationController?.navigationBar.addGestureRecognizer(self.navBarTapGestureRecognizer) hogeDisplay() } // navbar tap event @objc func navBarTapGesture(gestureRecognizer: UITapGestureRecognizer){ let touchLocation = gestureRecognizer.location(in: self.view) // 判定領域を拡大 let hogeBtnLocation = CGRect(x: hogeX - 10, y: hogeY - 10, width: hogeWidth + 10, height: hogeHeight + 10) if ((hogeBtnLocation.contains(touchLocation))) { self.hogeTaped(sender: hogeBtn) } } func hogeDisplay() { hogeBtn = UIButton(type: .custom) hogeBtn.imageView?.contentMode = .scaleAspectFit hogeBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30) let hogeBtnImg:UIImage = UIImage(named:"hoge")! hogeBtn.setBackgroundImage(hogeBtnImg, for: .normal) hogeBarButtonItem = UIBarButtonItem(customView: hogeBtn) hogeBarButtonItem.customView?.widthAnchor.constraint(equalToConstant: 30).isActive = true hogeBarButtonItem.customView?.heightAnchor.constraint(equalToConstant: 30).isActive = true hogeBtn.addTarget(self, action: #selector(hogeTaped(sender:)), for: .touchUpInside) self.navigationItem.rightBarButtonItem = hogeBarButtonItem } @objc func hogeTaped(sender: Any) { print("hogehoge...") } } |
それではまた〜