UIBarButtonItem: target-action not working?

后端 未结 11 931
无人及你
无人及你 2020-12-01 08:47

I\'ve got a custom view inside of a UIBarButtonItem, set by calling -initWithCustomView. My bar button item renders fine, but when I tap it, it doe

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 09:25

    I had a similar problem. And I initially followed the path suggested by @drawnonward, but then ran into trouble when I tried to have my action present a popover controller on an iPad: Using an embedded UIButton as a custom view means the UIButton is the sender of the event, and the popover controller’s presentPopoverFromBarButtonItem: method crashes when it tries to send it messages which are only appropriate to actual UIBarButtonItems.

    The solution I eventually found was to steal the image I wanted to use (the “info” icon) from a throwaway UIButton, and construct my UIBarButtonItem as follows:

    // Make the info button use the standard icon and hook it up to work
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
    UIBarButtonItem *barButton = [[[UIBarButtonItem alloc]        
          initWithImage:infoButton.currentImage
                  style:UIBarButtonItemStyleBordered
                 target:self
                 action:@selector(showInfo:)] autorelease];
    

    Using this initializer yields a bar button whose target and selector actually work. It is also easier than wrapping the image in a custom view, but that is just icing.

提交回复
热议问题