Swift Gesture Recognizer通过添加子视图

时间:2017-10-11 12:26:41

标签: ios swift uibutton uinavigationbar addsubview

我在titleView位置的navigationBar中添加了一个按钮。 然后我在这个按钮上添加了一个子视图。 我正在尝试添加与此视图关联的手势识别器(UIImageView),但未检测到点击。 是因为在NavigationBar中吗? 有没有办法让它发挥作用?

这是我的代码:

func createHeaderButton() {
    headerTitleBtn.setTitle(headerTitleBtnString, for: .normal)
    headerTitleBtn.titleLabel?.minimumScaleFactor = 0.5
    headerTitleBtn.titleLabel?.numberOfLines = 2
    headerTitleBtn.semanticContentAttribute = .forceRightToLeft
    let buttonImage = UIImageView()
    buttonImage.frame = CGRect(x: headerTitleBtn.frame.size.width, y: headerTitleBtn.frame.size.height/2 - 6, width: 12, height: 12)
    buttonImage.image = UIImage(named:"arrowDown")
    buttonImage.contentMode = .scaleAspectFit
    buttonImage.isUserInteractionEnabled = true
    buttonImage.backgroundColor = UIColor.red
    headerTitleBtn.contentMode = .scaleAspectFit
    let tapHedaerBtn = UIGestureRecognizer(target: self, action: #selector(headerBtnTapped))
    buttonImage.addGestureRecognizer(tapHedaerBtn)
    headerTitleBtn.addSubview(buttonImage)
}
@objc func headerBtnTapped() {
    print("here<")
}

我在viewDidLoad和viewWillAppear

中调用此函数

谢谢

---------------------------更新 这是我的解决方案: 我更改了代码,因此我不需要添加手势识别器和按钮上的所有内容:

    func createHeaderButton() {
    headerTitleBtn.setTitle(headerTitleBtnString, for: .normal)
    headerTitleBtn.titleLabel?.minimumScaleFactor = 0.5
    headerTitleBtn.titleLabel?.numberOfLines = 2
    headerTitleBtn.semanticContentAttribute = .forceRightToLeft
    headerTitleBtn.contentMode = .scaleAspectFit
    headerTitleBtn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 0)
    headerTitleBtn.setImage(UIImage(named:"arrowDown"), for: .normal)
    headerTitleBtn.imageEdgeInsets = UIEdgeInsets(top: 8, left: 15, bottom: 8, right: 8)
    headerTitleBtn.imageView?.contentMode = .scaleAspectFit
    headerTitleBtn.imageView?.tintColor = UIColor.white
    headerTitleBtn.tintColor = UIColor.white
}

0 个答案:

没有答案
相关问题