如何删除从视图控制器的iPhone上的工具栏按钮?
-
26-09-2019 - |
题
我有工作很大,用于将按钮添加到工具栏的代码:
NSArray* toolbarItems = [NSArray arrayWithObjects:flexibleSpace,shuffleBarItem,flexibleSpace,nil];
self.toolbarItems = toolbarItems;
不过,我也希望能够删除工具栏项目。当我使用以下方法,我的应用程序崩溃:
NSArray* toolbarItems = [NSArray arrayWithObjects:flexibleSpace,nil];
self.toolbarItems = toolbarItems;
有谁知道我怎么能动态地更改iPhone上的工具栏?
谢谢!
解决方案
更改它变成一个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
的两个实例
其他提示
要从前面或后面删除项目,则可以使用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;
请注意,你不应该发送给removeObjectAtIndex:
直接self.toolbarItems
(即使你使用上面的方法),因为toolbarItems
暴露作为NSArray
- you'll得到一个编译器警告,并可能崩溃(因为你有没有控制权是否会真正的幕后的NSMutableArray
来实现)。
不隶属于 StackOverflow