调整栏按钮大小的问题

时间:2017-12-31 16:33:06

标签: ios swift

我在创建一个让我感到非常难过的栏按钮时遇到了一些困难。我使用以下代码创建一个正确的条形按钮:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 22, height: 22))
button.setBackgroundImage(UIImage(named: "tune"), for: .normal)
button.addTarget(self, action:#selector(viewController.settingsBtnPressed), for:.touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

无论我设置宽度或高度,因为按钮大小不会改变。 VC位于导航控制器中。有没有人有任何见解或我可以采取的后续步骤?任何帮助将不胜感激

3 个答案:

答案 0 :(得分:0)

单击StoryBoard中的ViewController。转到"编辑" - > "嵌入" - >点击"导航控制器" 。然后将代码粘贴到您想要查看BarButton的ViewDidLoad方法中。

override func viewDidLoad() {
    super.viewDidLoad()
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 22, height: 22))
    button.setBackgroundImage(UIImage(named: "tune"), for: .normal)
    button.addTarget(self, action:#selector(ViewController.settingsBtnPressed), for:.touchUpInside)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}

答案 1 :(得分:0)

//此按钮的高度和最小值将受rightBarButtonItem

的影响

Button height is 100000

Button height is 0

[你可以]

    // Provide a vew to button 
    let tView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 40));
    tView.backgroundColor = UIColor.darkGray
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 22))
    //button.setBackgroundImage(UIImage(named: "tune"), for: .normal)
    button.backgroundColor = UIColor.green;
    button.addTarget(self, action:#selector(ViewController.settingsBtnPressed), for:.touchUpInside)
    // add btton to tView
    tView.addSubview(button)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: tView)

答案 2 :(得分:0)

原来问题是由于在iOS 11中如何处理条形按钮而产生的问题。UIBarButtonItem现在使用autolayout而不是帧。因此,以下代码允许您调整按钮的大小:

button.widthAnchor.constraint(equalToConstant: 22.0).isActive = true
button.heightAnchor.constraint(equalToConstant: 22.0).isActive = true
相关问题