2017-10-12 73 views
1

我一直在试图构建一个自定义的UINavigationBar,但我的button.frame输入没有任何效果。Swift 4 - 无法控制UIButton大小添加到UINavigationBar

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") 
} 

运行时代码(以上)出现这样的:

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

任何帮助非常感谢!

回答

0

添加约束到UIButton为:

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

希望它能帮助!

+0

它的工作!非常感谢! – Jake

+0

@Jake快乐编码:-) –