Egor Iskrenkov
Egor Iskrenkov

Reputation: 443

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. 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())

Here you can see the result on my iPhone:

I see this oversized image instead of 25x25 button

Upvotes: 0

Views: 1531

Answers (2)

Phineas Huang
Phineas Huang

Reputation: 833

This is work for me. Please try it. (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)]
}

Upvotes: 1

shivi_shub
shivi_shub

Reputation: 1058

Try to change the button type Replace .system to .custom . Also check the size of original image if it is very large.

Upvotes: 0

Related Questions