2使用的UIBarButtonItem的只加一次
问题描述:
我想补充项目之间的细线在我UIToolBar
所以我创造的,象这样一个自定义视图的UIBarButtonItem相同的自定义视图:2使用的UIBarButtonItem的只加一次
UILabel *separatorLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1, 44)];
separatorLabel.backgroundColor = [UIColor colorWithRGB:0xe5edec];
UIBarButtonItem *separator = [[UIBarButtonItem alloc] initWithCustomView:separatorLabel];
然后我加我分离的物品数组:
[items addObjectsFromArray:[NSMutableArray arrayWithObjects:someButton1, separator, somebutton2, separator, someButton3, nil]];
我认为这将增加2个到分离我的工具栏,但它只是增加了一个结尾。为什么是这样?
我可以通过创建2个重复标签和UIBarButtonItem来解决这个问题,但是还有其他更好的方法吗?
答
任何给定的UIView
实例只能在视图层次结构中出现一次。如果您考虑在UIView
上定义的API,这非常明显。例如,UIView
有一个frame
属性,它定义了它在超级视图中的位置。如果查看出现在两个地方,那么frame
属性就没有意义了。
所以你需要多个实例。您可以通过定义创建分离的方法简化你的代码:
- (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;
}
然后你就可以添加你的项目是这样的:
[items addObjectsFromArray:@[button1, [self newSeparator], button2, [self newSeparator]];
而且,你并不需要,如果你使用UILabel
”只重新显示背景颜色。您只能使用UIView
。
答
是的,你只是创建了一个UIBarButtonItem对象,所以它显示了一个。 我认为更好的方法是创建一个带有自定义标签的UIBarButtonItem子类,然后创建子类的两个对象。 我希望我的回答能帮助你。