UIButton的大小不会改变 - 斯威夫特

问题描述 投票:0回答:2

我正在尝试在我的iOS应用程序中设置自定义导航栏,但.frame = CGRect(...)不会更改我添加到其中的按钮的大小。按钮出现在导航栏内,但它们的大小错误,或者可能是约束,我不知道。

// 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)]
}

(我在viewDidLoad()中调用此函数)

在这里你可以在我的iPhone上看到结果:

ios swift uibutton
2个回答
1
投票

这对我有用。请试一试。 (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)]
}

0
投票

尝试将按钮类型Replace .system更改为.custom。如果原始图像非常大,也请检查原始图像的大小。

© www.soinside.com 2019 - 2024. All rights reserved.