How to adjust space between two UIBarButtonItem in rightBarButtonItems

前端 未结 14 2101
悲&欢浪女
悲&欢浪女 2020-12-08 06:44

I am using the following codes to add two button to self.navigationItem.rightBarButtonItems, and I think in iOS7, the space between two buttons are too wide, is there a way

14条回答
  •  旧时难觅i
    2020-12-08 07:23

    I gave up with fighting this bug, and came up with the following extension:

    import UIKit
    
    extension UIBarButtonItem {
    
        convenience init(buttonImage: UIImage?, target: Any?, action: Selector?) {
            let button = UIButton(type: .system)
            button.frame = CGRect(origin: CGPoint.zero, size: buttonImage != nil ? buttonImage!.size : CGSize.zero)
            button.setImage(buttonImage, for: .normal)
    
            if let action = action {
                button.addTarget(target, action: action, for: .touchUpInside)
            }
    
            self.init(customView: button)
        }
    
        public func updateButton(image: UIImage?) {
            if let button = self.customView as? UIButton {
                button.setImage(image, for: .normal)
    
                let size = image != nil ? image!.size : CGSize.zero
                let frame = button.frame
                button.frame = frame.insetBy(dx: ceil((frame.size.width - size.width) / 2), dy: ceil((frame.size.height - size.height) / 2))
            }
        }
    }
    

提交回复
热议问题