Change position of UIBarButtonItem in UINavigationBar

后端 未结 20 1493
一个人的身影
一个人的身影 2020-11-27 10:31

How can I change the position of a UIBarButtonItem in a UINavigationBar? I would like my button to be about 5px higher than its normal position.

20条回答
  •  一整个雨季
    2020-11-27 10:56

    In my case

    1. change barbuttonItem's frame to customize spaces

    2. Add, Remove barButtonItems dynamically.

    3. change tint colors by tableview's contentOffset.y

    like this

    If your minimum target is iOS 11, you can change the barButton frames in the viewDidLayoutSubviews

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        // Change the navigationBar item frames
        if let customView = wishButton.customView?.superview {
            customView.transform = CGAffineTransform(translationX: 7.0, y: 0)
        }
    
        if let customView = gourmetCountButton.customView?.superview {
            customView.transform = CGAffineTransform(translationX: 9.0, y: 0)
        }
    }
    

    But, it's Only worked on iOS 11.

    I also tried using the fixedSpace. But It didn't work in multiple navigationBarButton items.

     let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        space.width = -10
    

    So, I changed customView's width to adjust horizontal space.

    This is one of the my barButtonItem class

    final class DetailShareBarButtonItem: UIBarButtonItem {
    
    // MARK: - Value
    // MARK: Public
    ***// Change the width to adjust space***
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 32.0, height: 30.0))
    
    override var tintColor: UIColor? {
        didSet {
            button.tintColor = tintColor
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setButton()
    }
    
    required override init() {
        super.init()
        setButton()
    }
    
    
    // MARK: - Function
    // MARK: Private
    private func setButton() {
        // Button
        button.setImage( #imageLiteral(resourceName: "navibarIcShare02White").withRenderingMode(.alwaysTemplate), for: .normal)
        button.tintColor              = .white
        button.imageEdgeInsets        = UIEdgeInsetsMake(0, 1.0, 1.0, 0)
        button.imageView?.contentMode = .scaleAspectFill
    
        let containerView = UIView(frame: button.bounds)
        containerView.backgroundColor = .clear
        containerView.addSubview(button)
        customView = containerView
    }
    }
    

    This is the result.

    I tested on iOS 9 ~ 11, (Swift 4)

提交回复
热议问题