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

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

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

但我试图让它看起来像这样:

非常感谢任何帮助!

最佳答案

UIButton 添加约束:

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

希望对你有帮助!

关于ios - Swift 4 - 添加到 UINavigationBar 时无法控制 UIButton 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46701332/

相关文章:

ios - objective-c -具有多个测试输入的单元测试最佳实践

ios - 如何过滤一对多关系

ios - Swift4.2 : Why func gameDidEnd(_:) no need to use game parameter but still declare in the function?

ios - 以编程方式将 UIButton 添加到具有 Storyboard的自定义 ViewController

swift - tvOS - preferredFocusEnvironments 不工作

iphone - 隐藏导航栏点击不工作

ios - 为什么在横向时按下后退会删除所有导航栏信息?

ios - Tableview header 标签在中心对齐

iOS 7 SpriteKit - 创建游戏菜单/按钮(场景与更多 View Controller )

css - 居中对齐导航项