Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

swift - Change size and location of Navigation Bar Item Image

I have a Navigation Bar left button being created. I want to put my company logo there but when I use the storyboard and disable the button, it creates the logo with a tint. I found a thread that let me create the button and assign the button my logo and change the appearance of the logo based on the user's display settings. It changes the color of the logo and works perfectly. The only problem I am having is changing the size of the image and the location. The button is taking up the entire navigation bar and is centered rather than to the left.

Here is a custom class for the button that I am using:

import UIKit

class TintableBarButtonItem: UIBarButtonItem {

    private(set) var button: UIButton!

    override var tintColor: UIColor? {
        get { return button.tintColor }
        set { button.tintColor = newValue }
    }

    convenience init(button: UIButton) {
        self.init(customView: button)
        self.button = button
        button.imageView?.contentMode = .scaleAspectFit
        button.frame = CGRect(x: 0, y: 0, width: 34, height: 30)
    }

}

In my view controller in which I want the button to be used I have the following code:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let button = UIButton()
    button.frame = CGRect(x: 0.0, y: 0.0, width: 20, height: 20)
    let image = #imageLiteral(resourceName: "My Company Logo").withRenderingMode(.automatic)
    button.setImage(image, for: .normal)
        let barButton = TintableBarButtonItem(button: button)
        navigationItem.leftBarButtonItem = barButton
    
}

I have tried changing the frame in just the class, the frame in just the view controller, and changing the frame in both and can't seem to move the button or change the size. I could really use some help figuring this out. Thank you guys for all the help on this website. Learning so much.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...