【问题标题】:Add buttons to NavigationItem向 NavigationItem 添加按钮
【发布时间】:2017-12-18 09:54:10
【问题描述】:

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

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

【问题讨论】:

  • 你的 swift 版本是什么?
  • Swift 版本是 2.2
  • 是老项目吗
  • 尝试使用 self.on_clicked_btn(_:) 而不是 ViewController.on_clicked_btn(_:) 并告诉我
  • @ReinierMelian 它不会以任何方式工作,因为他没有初始化 navView rect。所以按钮和照片是在 navView 边界之外创建的

标签: ios swift xcode uinavigationcontroller uibutton


【解决方案1】:

这是因为您没有在以下位置初始化 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    相关资源
    最近更新 更多