1

我的代码非常适合向工具栏添加按钮:

NSArray* toolbarItems = [NSArray arrayWithObjects:flexibleSpace,shuffleBarItem,flexibleSpace,nil];
self.toolbarItems = toolbarItems;

但是,我也希望能够删除工具栏项目。当我使用以下方法时,我的应用程序崩溃:

NSArray* toolbarItems = [NSArray arrayWithObjects:flexibleSpace,nil];
self.toolbarItems = toolbarItems;

有谁知道我如何动态更改 iPhone 上的工具栏?

谢谢!

4

2 回答 2

1

将其更改为NSMutableArray.

NSMutableArray* _toolbarItems = [NSMutableArray arrayWithCapacity: 3]; 
[ _toolbarItems addObjects: flexibleSpace,shuffleBarItem,flexibleSpace,nil];

self.toolbarItems = _toolbarItems;

当您想从数组中删除项目时:

NSInteger indexOfItem = ...
[ _toolbarItems removeObjectAtIndex: indexOfItem ];

self.toolbarItems = _toolbarItems;

请注意,在这种情况下,您不应该使用removeObject,因为您的数组中有重复的对象,并且调用[ _toolbarItems removeObject: flexibleSpace ]实际上会删除flexibleSpace数组中的两个实例

于 2010-04-11T20:20:56.807 回答
1

要从前面或后面删除项目,您可以使用subarrayWithRange,即:

NSRange allExceptLast;
allExceptLast.location = 0;
allExceptLast.length = [self.toolbarItems count] - 1;
self.toolbarItems = [self.toolbarItems subarrayWithRange:allExceptLast];

如果要从中间删除对象,可以使用-[NSArray filteredArrayUsingPredicate:](可能过于复杂)或蛮力:

NSMutableArray *mutToolbarItems = [NSMutableArray arrayWithArray:self.toolbarItems];
[mutToolbarItems removeObjectAtIndex:<index of object>];
self.toolbarItems = mutToolbarItems;

Note that you shouldn't send removeObjectAtIndex: to self.toolbarItems directly (even if you use the above method), since toolbarItems is exposed as an NSArray--you'll get a compiler warning, and possibly a crash (since you have no control over whether it will actually be implemented as an NSMutableArray behind the scenes).

于 2010-04-11T22:53:20.833 回答