Change width of a UIBarButtonItem in a UINavigationBar

前端 未结 6 1624
囚心锁ツ
囚心锁ツ 2020-12-01 12:10

I am creating a UIBarButtonItem and adding it to my navigation bar like so:

(void)viewDidLoad { 

   ...

   // Add the refresh button to the navigation bar
         


        
6条回答
  •  粉色の甜心
    2020-12-01 12:57

    The key thing with this is to realise that you are changing the custom view's width, rather than the UIBarButton itself.

    The code is therefore:

    CGRect resizedFrame = myBarButtonItem.customView.frame;
    resizedFrame.size.width = myNewWidth;
    myBarButtonItem.customView.frame = resizedFrame;
    

    You will also need to trigger the layout change:

    [myNavigationBar setNeedsLayout];
    

    All this goes without saying that the layout is being done with Auto Sizing and frames. Incursions into navigation bars with Auto Layout yielded no success. See my question Auto Layout with UINavigationBar and UIBarButtonItem.

    Sorry just realised that my code is almost identical to @oscartzombie. Not intentional! I'll leave this answer as I think it's worth adding the layout and other points, in addition to explaining without reference to Interface Bulder or images specifically.

提交回复
热议问题