Aligning UIToolBar items

∥☆過路亽.° 提交于 2019-11-26 17:34:42

问题


I have three UIBarButtonItem created as below. They align left and I'd like to align center so there isn't a gap on the right side. I don't see an align property on UIToolBar. Is there another way to accomplish this?

//create some buttons
UIBarButtonItem *aboutButton = [[UIBarButtonItem alloc] initWithTitle:@"About" style:UIBarButtonItemStyleBordered target:self action:@selector(showAbout:)];
[toolbar setItems:[NSArray arrayWithObjects:settingsButton,deleteButton,aboutButton,nil]];
//Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];

回答1:


Add two UIBarButtonSystemItemFlexibleSpace items to your toolbar, to the left and right of your items

UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolbar setItems:[NSArray arrayWithObjects:flexibleSpace, settingsButton,deleteButton,aboutButton, flexibleSpace, nil]];

Adding these as you would any other toolbar items will distribute space evenly between the two of them.




回答2:


This can also be done right from a storyboard.

Just drag and drop items in the toolbar, and turn some of them into flexible or fixed space to get the desired effect. See the two examples below.




回答3:


In Xamarin iOS

Right aligned:

yourBar.SetItems(new [] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), yourButton }, false);

Center Aligned:

var flexibleSpace = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace);
yourBar.SetItems(new [] { flexibleSpace, yourButton, flexibleSpace}, false);



回答4:


Swift version:

    let toolbar = UIToolbar(frame: CGRectMake(0, 0, viewController.view.frame.size.width, 35.0))
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: viewController, action: nil)
    let button1 = UIBarButtonItem(title: "A", style: UIBarButtonItemStyle.Plain, target: viewController, action: foo)
    let button2 = UIBarButtonItem(title: "B", style: UIBarButtonItemStyle.Plain, target: viewController, action: bar)
    let button3 = UIBarButtonItem(title: "C", style: UIBarButtonItemStyle.Plain, target: viewController, action: blah)
    toolbar.items = [button1, flexibleSpace, button2, flexibleSpace, button3]


来源:https://stackoverflow.com/questions/602717/aligning-uitoolbar-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!