Ios 切换到控制唯一表视图单元格
我只是在我的单元格中添加了一个开关,我希望每个开关都能获取nique单元格的信息并控制唯一的单元格。我的代码如下: 在cellforrowatinexpath方法中,我创建了一个开关Ios 切换到控制唯一表视图单元格,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我只是在我的单元格中添加了一个开关,我希望每个开关都能获取nique单元格的信息并控制唯一的单元格。我的代码如下: 在cellforrowatinexpath方法中,我创建了一个开关 UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero]; cell.accessoryView = switchView; [switchView setOn:NO animated:NO]; [swit
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchView;
[switchView setOn:NO animated:NO];
[switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
然后我编写了开关的方法。一切正常,但我拿不到开关的电池
- (void) switchChanged:(id)sender withIdentifier:(NSString*)locationName{
UISwitch* switchControl = sender;
if (switchControl.on) {
NSIndexPath *indexPath = [self.AlarmsTableView indexPathForCell:cell];
NSLog(@"the switch is on for row number: %d",indexPath.row);
}
else{
NSLog(@"switch off");
}
}
你必须在这里使用标签的概念。 给交换机一个标签,通常是XPath中的单元格
switchView.tag=indexPath.row;
在函数中,使用标记
int switchTag=[sender tag];
这就是你的手机
NSIndexPath *myIP = [NSIndexPath indexPathForRow:switchTag inSection:0] ;
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:myIP];
在cellForRowAtIndexPath中添加此行:
在开关事件方法中,执行以下操作:
UISwitch *tswitch = (UISwitch *)sender;
//tswitch.tag; is your row.
如果tableView中只有一个分区,请执行以下操作:
NSIndexPath *myIP = [NSIndexPath indexPathForRow: tswitch.tag inSection:0] ;
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath: myIP];
我谦卑地不同意标签解决方案。当然,如果你只有一个部分,它是有效的,但它不是最好的解决方案 您应该改为将UITableViewCell子类化,并将开关放在那里。然后,单元格处理开关,最好告诉它自己创建的是委托,并设置为处理所创建的tableView的ViewController 切换到:BOOLonOrOff forCell:yoursubasscell*单元格
然后,您可以通过tableView方法indexPathForCell轻松确定单元格的indexpathCellForRowatineXpath:switchTag,应该是indexpath。switchTag?CellForRowatineXpath需要传递一个indexpath,而不是整数。遗憾的是,apple没有一个可视的界面来为多个节的情况创建NSIdexPath。我尝试了代码nsindepath*myIP=[nsindepath-indexPathForRow:switchTag-instation:0];但是得到错误消息,它实际上是有效的!甚至我也没有看到任何创建索引路径indexPathWithIndex:indexPathWithIndexes:length:initWithIndex:initWithIndexes:length:其中包括inSection,当我复制和粘贴时,它可以工作!当我成功获取行号时,如何获取具有索引路径的单元格?@JimLiu使用此解决方案无法获得。请参阅我的答案,了解如何使之成为可能。我看到的表格视图中有两个部分。我将创建一个子类的细胞,并添加方法和设置委托,看看它是否工作。
NSIndexPath *myIP = [NSIndexPath indexPathForRow: tswitch.tag inSection:0] ;
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath: myIP];
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Your SwitchView
switchView.tag = indexPath.row;
}
-(void) switchChanged:(id)sender withIdentifier:(NSString*)locationName
{
UISwitch* switchControl = (UISwitch *)sender;
if(switchControl.on)
{
//NSIndexPath *indexPath = [self.AlarmsTableView indexPathForCell:cell];
NSLog(@"the switch is on for row number: %d",switchControl.tag);
}
else
{
NSLog(@"switch off");
}
}