繁体   English   中英

如何使用Swift 3.0使用Swift 3.0更改iOS应用程序中按钮的高度和宽度

[英]How to change the height and width of a button in iOS app using Swift 4.0 which is developed using Swift 3.0

我是iOS开发的新手,我应该修复使用Swift 3.0和Xcode 8制作的iOS应用程序中的一些错误,它几乎可以正常工作。 但是当我用Xcode 9和Swift 4.0打开它时,它显示出一些与之前不同的按钮。

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

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)

它什么都没改变。 我的问题是如何解决这个错误。 任何建议,答案都非常感谢,如果给出的细节不够,请提及。 谢谢!

迅捷4:

button.widthAnchor.constraint(equalToConstant: 30.0).isActive = true
button.heightAnchor.constraint(equalToConstant: 20.0).isActive = true

与iOS 11开始,观点添加使用工具栏UIBarButtonItem使用UIBarButtonItem(customView:)现在制定了使用自动布局。 您应该在button上添加大小限制。 例如:

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

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

有关更多信息,请参阅WWDC 2017会话更新iOS 11应用程序

您可以使用Xcode中的故事板自定义按钮的宽度和高度。 只需选择您的按钮并打开此窗口即可。 约束布局

之后只需添加高度限制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM