简体   繁体   中英

iPhone Toolbar button spacing

有没有办法让工具栏空间中的UIBarButtonItem自己均匀分布?

Drop a Flexible Space bar button item in between your UIBarButtonItems. This is pretty easy to do in IB, look down the bottom of the controls.

If you want to do this programtically, this code should help:

UIBarButtonItem* button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button1" style:UIBarButtonItemStyleBordered target:self action:@selector(button1Action)];
UIBarButtonItem* button2 = [[UIBarButtonItem alloc] initWithTitle:@"Button2" style:UIBarButtonItemStyleBordered target:self action:@selector(button2Action)];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[myToolbar setItems:[NSArray arrayWithObjects:button1, flexibleSpace, button2, nil]];

Ignore the width on UIBarButtonItem suggestion; this is not the correct approach as recommended by Apple and will not work if you want to add further icons.

The correct approach is to add a "Flexible space" (technically another button!) in between each button. You see it in Interface Builder, or it can be added directly in code if needed.

Yup. Create a UIBarButtonItem with the -initWithBarButtonSystemItem: method using UIBarButtonSystemItemFlexibleSpace , and insert that between each of your actual toolbar items. Eg:

UIBarButtonItem *flexSpace = [[UIBarButton alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace];
myToolbar.items = [NSArray arrayWithObjects:buttonOne,flexSpace,buttonTwo,flexSpace,buttonThree,nil];
[flexSpace release];

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