iOS 7 BarButtonItem with image and title

前端 未结 4 962
时光说笑
时光说笑 2020-12-08 08:49

I\'m trying to figure out how can I achieve something like this:

\"enter

This

4条回答
  •  清歌不尽
    2020-12-08 08:58

    You can embed a UIButton as a custom view inside your UIBarButtonItem. You can create your UIButton however you want, including with an image and text, using -setImage:forState: and -setTitle:forState:.

    UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [customButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
    [customButton setTitle:@"Button" forState:UIControlStateNormal];
    [customButton sizeToFit];
    UIBarButtonItem* customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
    self.navigationItem.leftBarButtonItem = customBarButtonItem; // or self.navigationItem.rightBarButtonItem
    

    Note that when doing this, you'll need to attach your IBAction methods to customButton, not to customBarButtonItem.

    For more info, see the documentation for initWithCustomView:.

    You can also do all of this in interface builder just by dragging a UIButton to the left bar button/right bar button slot on a navigation bar.

提交回复
热议问题