2017-10-19 45 views
2

我对iOS开发是全新的,我应该修复使用Swift 3.0制作的iOS应用程序中的一些错误和Xcode 8,它工作得很好。但是当我用Xcode 9和Swift 4.0打开它时,它显示了一些与以前不同的按钮方式。如何使用Swift 3.0开发的Swift 4.0更改iOS应用程序中按钮的高度和宽度

以下是其中一个按钮的源代码。

let button: UIButton = UIButton.init(type: UIButtonType.custom) 
    //set image for button 
    button.setImage(UIImage(named: "menu.png"), for: UIControlState()) 
    button.frame = CGRect(x: 0, y: 0, width: 30, height: 23) 
    let barButton = UIBarButtonItem(customView: button) 
    button.addTarget(self, action: #selector(ViewController.shareButtonPressed), for: UIControlEvents.touchUpInside) 

    self.navigationItem.leftBarButtonItem = barButton 

此代码位于ViewDidLoad方法内部。我的问题是,当我删除,

button.setImage(UIImage(named: "menu.png"), for: UIControlState()) 

消失的按钮,但是当我改变高度和宽度,

button.frame = CGRect(x: 0, y: 0, width: 30, height: 23) 

它改变不了什么。 我的问题是我该如何解决这个错误。任何建议,答复高度赞赏,如果给出的细节不够,请提及。谢谢!

回答

1

从iOS 11开始,使用UIBarButtonItem使用UIBarButtonItem(customView:)添加到工具栏的视图现在使用自动布局进行布置。您应该在button上添加尺寸限制。例如:

button.widthAnchor.constraintEqualToConstant(30.0).isActive = true 
button.heightAnchor.constraintEqualToConstant(23.0).isActive = true 

否则,自动布局将使用您的标题视图的内在内容大小,这可能不是您所期望的。

欲了解更多信息,请参阅WWDC 2017会议Updating your app for iOS 11

+0

谢谢你的答案。它的工作原理,因为这 '如果#available(的iOS 9.0,*){ button.widthAnchor.constraint(equalToConstant:20.0).isActive =真 }其他{// 后退在早期版本 }' –

+0

是。锚点是在iOS 9中引入的。如果你的目标是低于这个目标,你需要'#available',但是如前所述,约束大小只能在iOS 11及更高版本上应用。 – beyowulf

0

SWIFT 4:

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