向NavigationItem添加按钮

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了向NavigationItem添加按钮相关的知识,希望对你有一定的参考价值。

我尝试在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

有任何想法吗?谢谢你的帮助。

答案

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

let navView = UIView()

替换为

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

更换箱架:

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

和相框

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

以上是关于向NavigationItem添加按钮的主要内容,如果未能解决你的问题,请参考以下文章

Android:向活动添加片段

self.navigationItem.rightBarButtonItem = 按钮不起作用?

当我向 navigationItem 添加更多按钮时,如何使我的 navigationItem.titleView 居中?

添加一个动作以快速向后滑动 4

在片段中添加按钮? [复制]

如何向 UILocalNotification 警报添加操作按钮/操作?