向NavigationItem添加按钮

时间:2017-12-18 09:54:11

标签: ios swift xcode uinavigationcontroller uibutton

我尝试在NavigationItem上添加按钮和ImageView。对于这个对象,我为它添加了两个函数TouchUp。我在uiview上添加了这两个对象。 UIView我添加到UINavigaionItem。我添加了UIGesture for ImageView和TouchUp action for button。但是按钮和ImageView没有点击。 代码如下:

    let navView = UIView()
    navView.userInteractionEnabled = true

    let btn = UIButton(type: UIButtonType.Custom) as UIButton
    btn.addTarget(self, action: #selector(ViewController.on_clicked_btn(_:)), forControlEvents: UIControlEvents.TouchUpInside)
    btn.frame = CGRectMake(-65, -22, 130, 42)
    btn.setTitle("title", forState: .Normal)
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center
    btn.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
    btn.titleLabel?.backgroundColor = UIColor.clearColor()

    photo.frame = CGRect(x: -110, y: -18, width: 33, height: 33)
    photo.layer.borderWidth = 0.5
    photo.layer.masksToBounds = false
    photo.layer.borderColor = UIColor.grayColor().CGColor
    photo.layer.cornerRadius = self.photo_avatar.frame.height/2
    photo.clipsToBounds = true

    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.on_clicked_photo(_:)))
    photo.addGestureRecognizer(tapRecognizer)
    photo.userInteractionEnabled = true

    navView.addSubview(photo)
    navView.addSubview(btn)
    self.navigationItem.titleView = navView

有什么想法吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

这是因为你没有初始化UIIview rect:

let navView = UIView()

将其替换为

let navView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 168, height: 40))

将bin框架替换为:

btn.frame = CGRect(x: 38, y: 0, width: 130, height: 42)

和相框

photo.frame = CGRect(x: 0, y: 0, width: 33, height: 33)