ios - 向 NavigationItem 添加按钮

标签 ios swift xcode uinavigationcontroller uibutton

我尝试在 NavigationItem 上添加按钮和 ImageView。对于这个对象,我为它添加了两个函数 TouchUp。这两个对象是我在 uiview 上添加的。我添加到 UINavigaionItem 的 UIView。我为 ImageView 添加了 UIGesture,为按钮添加了 TouchUp 操作。但是按钮和 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 in:

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)

关于ios - 向 NavigationItem 添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47865820/

相关文章:

swift - 更改枚举的功能

ios - 更新 UITextView.text 属性时未调用 textViewDidChange 方法?

ios - Xcode导出/上传错误: Your session has expired.请登录

iphone - 应用程序仅在iPhone设备上崩溃而不在模拟器中崩溃

Android、iOS 和 WP8 : read QR code -> open app or go to the store

ios - 将 distanceFromLocation 转换为 Int

ios - Xcode 5 - 如何添加标题搜索路径和使用 GDataXMLNode

ios - 从 UIImage 访问地理位置

ios - 'NSLog' 不可用 : Variadic function is unavailable in swift

ios - 我很快收到不受支持的参数组合 CGBitmap 错误