在TapController中将自定义视图添加到自定义视图

时间:2017-11-12 07:35:39

标签: ios swift uiview uinavigationcontroller uitapgesturerecognizer

我正在尝试在导航栏中的自定义视图中添加操作。我让它显示得很好,但我无法弄清楚如何添加点按动作。

我尝试在视图中添加一个按钮并在那里处理它。我已经尝试使我的导航控制器成为自定义视图的委托,我尝试在导航控制器中向视图添加轻击手势识别器。没有任何效果。非常感谢任何建议或反馈。

谢谢!

我的自定义导航控制器:

class MainNavVC: UINavigationController {

    var loadStatus = LoadStatus()

    override func viewDidLoad() {
        super.viewDidLoad()

        // load status
        loadStatus.bounds = CGRect(x: -24, y: -6, width: 0, height: 0)
        let loadStatusButton = UIBarButtonItem(customView: loadStatus)
        self.viewControllers.last?.navigationItem.leftBarButtonItem = loadStatusButton

        let tap = UITapGestureRecognizer(target: self, action: #selector(loadStatusPressed))
        loadStatus.addGestureRecognizer(tap)
        loadStatus.isUserInteractionEnabled = true
    }

    @objc func loadStatusPressed(recognizer: UIGestureRecognizer) {
        print("tapped")
        let alert = UIAlertController(title: "Load Status", message: "When you are under a load, you are being tracked by a shipper.", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    }
}

我的自定义视图:

class LoadStatus: UIView {

    @IBOutlet var contentView: UIView!

    private func commonInit(){
        Bundle.main.loadNibNamed("LoadStatus", owner: self, options: nil)
        addSubview(contentView)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder ) {
        super.init(coder: aDecoder)
        commonInit()
    }

}

2 个答案:

答案 0 :(得分:1)

UIBarButtonItem添加点击手势识别器似乎有点奇怪,默认情况下,在创建新的UIBarButtonItem时,编程方式如您的代码段所示,使用init(barButtonSystemItem:target:action:) ,您可以为条形按钮添加所需的操作,例如:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // like this:
        let loadStatusButton = UIBarButtonItem(title: "Button Title", style: .plain, target: self, action: #selector(loadStatusPressed))


        // ...
    }

    @objc func loadStatusPressed() {
        print("tapped")
        let alert = UIAlertController(title: "Load Status", message: "When you are under a load, you are being tracked by a shipper.", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    }
}

为了设置自定义视图,您只需添加:

loadStatusButton.customView = loadStatus

因此,无需为条形按钮添加点按手势。

答案 1 :(得分:1)

从iOS11开始,您需要为自定义视图提供宽度和高度约束,例如:

loadStatus.widthAnchor.constraint(equalToConstant: 44).isActive = true
loadStatus.heightAnchor.constraint(equalToConstant: 44).isActive = true

否则您的自定义视图可能是可见的,但内部为零。这是一个错误。

(我假设UINavigationController现在(iOS11 +)基于约束而不是之前!?)

相关问题