简体   繁体   中英

How to update a bar button item in a toolbar

I have a single playback controller in my app on the navigation bar and is easily found in its implementation file. So I've tried to add a toolbar and move the playback controls to that toolbar, but I don't know how to reference it programmatically and therefore cannot update the image used to indicate if music can be paused or played.

You can do this a couple of ways, one is by setting the image of the UIBarButtonItem not to be confused with the backgroundImage of a button. You can add a bar button like so:

UIBarButtonItem *barButton1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"camera.png"] style:UIBarButtonItemStylePlain target:self action: @selector(pressButton1:)];

The image should be a grayscale image somewhere around 30 x 30 in size much like a tab bar icon. Declare the bar button in the interface file and you can set the image like this:

[barButton1 setImage:[UIImage imageNamed:@"Chats.png"]];

The other way you can do this is by using a custom UIButton like so:

button1 = [UIButton buttonWithType:UIButtonTypeCustom]; button1.frame = CGRectMake(0, 0, 64, 30); [button1 setBackgroundImage:[UIImage imageNamed:@"camera.png"] forState: UIControlStateNormal]; [button1 setBackgroundImage:[UIImage imageNamed:@"Chats.png"] forState: UIControlStateSelected]; [button1 setTitle:@"Camera" forState:UIControlStateNormal]; button1.titleLabel.font = [UIFont boldSystemFontOfSize:12]; [button1 addTarget:self action:@selector(pressButton1:) forControlEvents: UIControlEventTouchUpInside];

UIBarButtonItem *barButton1 = [[UIBarButtonItem alloc] initWithCustomView:button1];

Declare button1 in the interface file and then you can change the image like so:

[button1 setSelected:TRUE];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM