简体   繁体   English

UIButton的大小不变-Swift

[英]The size of the UIButton doesn't change - Swift

I'm trying to setup the custom navigation bar in my iOS app, but .frame = CGRect(...) doesn't change the size of buttons that I added to it. 我正在尝试在iOS应用中设置自定义导航栏,但是.frame = CGRect(...)不会更改我添加到其中的按钮的大小。 Buttons appeared inside the navigation bar, but they have wrong size, or maybe constraints, I don't know. 按钮出现在导航栏中,但是我不知道它们的大小或约束是否正确。

// Setting up the Navigation Bar
private func setupNavigationBar() {
    // Remove the shadow under the Navigation Bar
    self.navigationController?.navigationBar.shadowImage = UIImage()

    let addButton = UIButton(type: .system)
    addButton.setImage(UIImage(named: "ic_add")?.withRenderingMode(.alwaysOriginal), for: .normal)
    addButton.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

    let settingsButton = UIButton(type: .system)
    settingsButton.setImage(UIImage(named: "ic_settings")?.withRenderingMode(.alwaysOriginal), for: .normal)
    settingsButton.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

    navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: settingsButton), UIBarButtonItem(customView: addButton)]
}

(I call this function inside the viewDidLoad() ) (我在viewDidLoad()内部调用此函数)

Here you can see the result on my iPhone: 在这里,您可以在我的iPhone上看到结果:

我看到此尺寸过大的图片,而不是25x25的按钮

This is work for me. 这对我来说是工作。 Please try it. 请尝试一下。 (iOS 11) (iOS 11)

    private func setupNavigationBar() {
    // Remove the shadow under the Navigation Bar
    self.navigationController?.navigationBar.shadowImage = UIImage()

    let addButton = UIButton(type: .custom)
    addButton.setImage(UIImage(named: "ic_add")?.withRenderingMode(.alwaysOriginal), for: .normal)
    addButton.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

    let settingsButton = UIButton(type: .custom)
    settingsButton.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
    settingsButton.setImage(UIImage(named: "ic_settings")?.withRenderingMode(.alwaysOriginal), for: .normal)
    let menuBarItem = UIBarButtonItem(customView: settingsButton) // new line
    let currWidth = menuBarItem.customView?.widthAnchor.constraint(equalToConstant: 10) // new line
    currWidth?.isActive = true // new line
    let currHeight = menuBarItem.customView?.heightAnchor.constraint(equalToConstant: 10) // new line
    currHeight?.isActive = true // new line

    navigationItem.rightBarButtonItems = [
        menuBarItem, // modify
        UIBarButtonItem(customView: addButton)]
}

Try to change the button type Replace .system to .custom . 尝试将按钮类型Replace .system更改为.custom。 Also check the size of original image if it is very large. 如果原始图像太大,也请检查其大小。

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

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