Swift 4 - 添加到UINavigationBar时无法控制UIButton大小

时间:2017-10-12 04:16:09

标签: ios uibutton uinavigationbar xcode9 swift4

我一直在尝试构建自定义UINavigationBar,但我的button.frame输入没有任何效果。

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton(type: .custom)
    button.setImage(UIImage(named: "I_sent"), for: .normal)
    button.addTarget(self, action: #selector(action), for: .touchUpInside)

    // This doesn't seem to have an effect:
    button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    button.contentMode = .scaleAspectFit

    let item = UIBarButtonItem(customView: button)
    navigationItem.rightBarButtonItem = item
}

@objc func action() {
    print("Action")
}

运行时代码(如上所示):

但我想让它看起来像这样:

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

将约束添加到UIButton

button.widthAnchor.constraint(equalToConstant: button.frame.size.width).isActive = true
button.heightAnchor.constraint(equalToConstant: button.frame.size.height).isActive = true

希望它有所帮助!