Question

I want to add a thin line between items in my UIToolBar so I'm creating a UIBarButtonItem with a custom view like so:

UILabel *separatorLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1, 44)];
separatorLabel.backgroundColor = [UIColor colorWithRGB:0xe5edec];
UIBarButtonItem *separator = [[UIBarButtonItem alloc] initWithCustomView:separatorLabel];

Then I add my separator to the items array:

[items addObjectsFromArray:[NSMutableArray arrayWithObjects:someButton1, separator, somebutton2, separator, someButton3, nil]];

I thought this would add 2 separators to my toolbar but it only adds the one at the end. Why is this?

I can fix this by creating 2 duplicate labels and UIBarButtonItem's, but is there any other better way?

Was it helpful?

Solution

Any given instance of UIView can only appear in once in the view hierarchy. If you think about the APIs defined on UIView, this is fairly obvious. For example, UIView has a frame property which defines it's location in the superview. The frame property wouldn't make sense if the viewed appeared in two places.

So you need multiple instances. You can streamline your code by defining a method that creates separators:

- (UILabel *)newSeparator
{
    UILabel *separatorLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1, 44)];
    separatorLabel.backgroundColor = [UIColor colorWithRGB:0xe5edec];
    UIBarButtonItem *separator = [[UIBarButtonItem alloc] initWithCustomView:separatorLabel];
    return separator;
}

And then you can add your items like this:

[items addObjectsFromArray:@[button1, [self newSeparator], button2, [self newSeparator]];

Also, you don't need to use UILabel if you're only displaying a background color. You can just use UIView.

OTHER TIPS

Yes,you just created only one UIBarButtonItem object,so it showed one. I think the better way is creating a UIBarButtonItem subclass with custom label,then create two objects of the subclass. I hope my answer can help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top