Change Spacing Between UIBarButtonItems in iOS 8

后端 未结 3 537
执念已碎
执念已碎 2021-01-03 19:49

I have a UINavigationItem on my view controller, and I am trying to reduce the spacing between my two RightBarButtonItems. Here is

相关标签:
3条回答
  • 2021-01-03 20:08

    Thanks to @Fogmeister's help, I figured out that the width of the view1 and view2 objects, which are UIButtons, was too large. That was why there was abnormal spacing between them. Here is my final code:

        // Get the first button's image
        let view1Img = UIImage(named: "Image1")!
        
        // Create the first button
        let view1 = UIButton(frame: CGRect(x: 0, y: 0, width: view1Img.size.width, height: view1Img.size.height))
        
        // Get the second button's image
        let view2Img = UIImage(named: "Image2")!
        
        // Create the second button
        let view2 = UIButton(frame: CGRect(x: 0, y: 0, width: view2Img.size.width, height: view2Img.size.height))
        
        // Create two UIBarButtonItems
        let item1 = UIBarButtonItem(customView: view1)
        let item2 = UIBarButtonItem(customView: view2)
        
        // Set 26px of fixed space between the two UIBarButtonItems
        let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        fixedSpace.width = 26.0
        
        // Set -7px of fixed space before the two UIBarButtonItems so that they are aligned to the edge
        let negativeSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        negativeSpace.width = -7.0
        
        // Add the rightBarButtonItems on the navigation bar
        viewController.navigationItem.rightBarButtonItems = [negativeSpace, item2, fixedSpace, item1]
    

    I create the background image for the first UIButton and then use its size to create the frame for that UIButton. I perform the same actions for the second UIButton. Then, I create UIBarButtonItems from the two UIButtons. After that, I create 26px of fixed space and then -7.0px of fixed space. The purpose of the former is to create a certain amount of space between the two buttons. The purpose of the latter is to move all UIBarButtonItems over to the right. Then, I add all of the UIBarButtonItems as rightBarButtonItems in a particular order so I get the look that I want.

    It works great now! Thanks for all of the help, Fogmeister!

    0 讨论(0)
  • 2021-01-03 20:12

    Another way is just by changing the Left and Right Image Inset in IB.

    0 讨论(0)
  • 2021-01-03 20:32

    From the docs for UIBarButtonItem...

    enter image description here

    If the value is 0.0 or negative, the item sets the width of the combined image and title to fit.

    If you set the width to -20.0 it will ignore it and use the standard width.

    What is it you are trying to achieve with a negative width anyway? I'm almost certain there will be a better way.

    0 讨论(0)
提交回复
热议问题