suj*_*uji 2 iphone xcode objective-c
对于您的专家来说,这可能是一个简单的问题,但我无法找出正确的解决方案.
在我的应用程序中,我创建了一个表视图来列出一个项目.
在单元格的第一行有一个switch(ON/OFF).
因此我的客户端需要在切换时隐藏底部单元格(除了第零个单元格)并在切换时OFF显示所有单元格ON.
我通过代码创建了切换.
任何人都可以帮我解决这个问题吗?
提前致谢.
numberOfRows dataSource方法 - 使其返回1和reloadTableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/// ....
self.switchView = [[[UISwitch alloc] initWithFrame:CGRectZero]autorelease];
cell.accessoryView = self.switchView;
[self.switchView setOn:NO animated:NO];
[self.switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
//....
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if [self.switchView.on]
return 1;
else
{
// normal code return
}
}
- (void) switchChanged:(id)sender {
[self.tableView reloadData];
}
Run Code Online (Sandbox Code Playgroud)
您可以使用insertRowsAtIndexPaths,这不仅会添加,还会添加新行的动画
首先将目标添加UIControlEventTouchUpInside到UISwitch.
[switch addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];
- (void)switchChange :( UISwitch*)sender {
Run Code Online (Sandbox Code Playgroud)isSwitchOn = sender.on; //edited [myTable beginUpdates]; NSIndexPath *row1 = [NSIndexPath indexPathForRow:1 inSection:0]; NSIndexPath *row2 = [NSIndexPath indexPathForRow:2 inSection:0]; //you may add as many row as you want here. [myTable insertRowsAtIndexPaths:[NSArray arrayWithObjects:row1,row2,nil] withRowAnimation:UITableViewRowAnimationMiddle]; [myTable endUpdates];}
并确保您将添加要插入的行数 numberOfRowsInSection:
(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
if(isSwitchOn)返回1;
否则返回3; //打开后会有多少行
}
您可能需要检查[myTable insertSections:withRowAnimation:以插入另一个部分并执行与上面相同的操作.但要记住要说明你要添加多少部分numberOfSectionsInTableView:
更新:
deleteRowsAtIndexPaths:如果关闭则执行.
- (void)switchChange :( UISwitch*)sender {
Run Code Online (Sandbox Code Playgroud)isSwitchOn = sender.on; if(isSwitchOn){ [myTable beginUpdates]; NSIndexPath *row1 = [NSIndexPath indexPathForRow:1 inSection:0]; NSIndexPath *row2 = [NSIndexPath indexPathForRow:2 inSection:0]; //you may add as many row as you want here. [myTable insertRowsAtIndexPaths:[NSArray arrayWithObjects:row1,row2,nil] withRowAnimation:UITableViewRowAnimationMiddle]; [myTable endUpdates]; } else{ [myTable beginUpdates]; NSIndexPath *row1 = [NSIndexPath indexPathForRow:1 inSection:0]; NSIndexPath *row2 = [NSIndexPath indexPathForRow:2 inSection:0]; //you may add as many row as you want here. [myTable deleteRowsAtIndexPaths:[NSArray arrayWithObjects:row1,row2,nil] withRowAnimation:UITableViewRowAnimationFade]; [myTable endUpdates]; }}