如何在iOS中向UITable中的几行添加UISWitch?
我有一个如何在iOS中向UITable中的几行添加UISWitch?,ios,iphone,xcode,uitableview,ipad,Ios,Iphone,Xcode,Uitableview,Ipad,我有一个UITableView,它包含这么多行。在我的屏幕中,可以为UITableView中的几行添加UISwitch。请告诉我如何做 我是否应该使用ui开关创建自定义单元格&显示或隐藏ui开关 我是否应该直接从cellforrowatinexpath:中的代码添加UISwitch 有什么建议吗 编辑: 我已经尝试过这个代码,但它不起作用 SettingsCell *cell; static NSString *CellIdentifier = @"SettingCell"; if (
UITableView
,它包含这么多行。在我的屏幕中,可以为UITableView
中的几行添加UISwitch
。请告诉我如何做
- 我是否应该使用
&显示或隐藏ui开关创建自定义单元格
ui开关
- 我是否应该直接从
中的代码添加UISwitchcellforrowatinexpath:
SettingsCell *cell;
static NSString *CellIdentifier = @"SettingCell";
if (cell == nil)
{
cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleDefault];
[tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
}
if(indexPath.row==2 || indexPath.row==3)
{
cell.switch_value.hidden=false;
}
else
{
cell.switch_value.hidden=true;
}
cell.label_text.text = [VALUES objectAtIndex:indexPath.row];
return cell;
如果要创建新单元格,则应仅将该单元格用于所需的行。对于其余的行,您不应该痛苦地隐藏开关
如果直接从
单元格中的代码创建UISwitch
,则重新使用单元格时应小心。如果两种单元格类型使用不同的标识符,显示/隐藏问题将得到解决。这两种解决方案在这里都有效:您可以在UITableViewCell
中添加UISwitch
,在cellForRowIndexPath:
:创建新的UISwitch
之前,请仔细检查是否存在以前创建的UISwitch
第二种解决方案是使用自定义的UITableViewCell
子类。
我更喜欢此解决方案,因为您不必强制转换子视图或使用viewWithTag:
方法,甚至不必检查自定义子视图是否已创建
您应该创建一些simples子类,例如PickerCell、SwitchCell、TextFieldcell:这样您就有了自己的一组自定义UITableViewCell
子类,可以在所有项目中使用
假设已注册重用标识符,请尝试以下操作:=
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SettingCellIdentifier = @"SettingCell";
static NSString *StandardCellIdentifier = @"StandardCell";
if (indexPath.row == 2 || indexPath.row == 3) {
SettingsCell *cell = (SettingsCell *)[tableView dequeueReusableCellWithIdentifier:SettingCellIdentifier forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleDefault];
[tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
cell.label_text.text = [VALUES objectAtIndex:indexPath.row];
// Do whatever you want with the switch here
return cell;
}
else
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:StandardCellIdentifier forIndexPath:indexPath];
// instantiate a regular UITableViewCell
cell.label_text.text = [VALUES objectAtIndex:indexPath.row];
return cell;
}
}
和我一样。我用UISwith创建了一个自定义单元格,显示或隐藏它取决于单元格我用一些代码示例编辑了我的答案。不要在cellForRowAtIndexPath中添加开关-单元格可以重用,然后再添加一次?或者你必须确保你只在它还没有出现的时候才添加它?这会出错……您不必多次添加它,因为只有在您还没有可用的单元时,才使用dequeueReusableCellWithIdentifier
分配该单元。但是如果在您将该单元出列时添加它,您将遇到我描述的问题-当然不是在cell awakeFromNib函数中创建它时,这不是您为解决方案1编写的内容。我没有详细解释第一个解决方案的todo列表,但在本例中,您是对的,您需要测试您的ui开关
子视图是否已经存在。因此,第二种方法更容易。我编辑了我的答案,以反映第一种方法的限制,谢谢:)