我在自定义 UITableViewCell
中有一个 UISwitch
(我称之为 RootLabeledSwitchTableCell
的子类)。
单元格包含彼此相邻的 UILabel
和 UISwitch
。
我有一个名为 keychainSwitch
的 @property
,它指向此自定义单元格内的开关:
@interface RootLabeledSwitchTableCell : UITableViewCell {
IBOutlet UILabel *textLabel;
IBOutlet UISwitch *labeledSwitch;
}
@property (nonatomic, retain) IBOutlet UILabel *textLabel;
@property (nonatomic, retain) IBOutlet UISwitch *labeledSwitch;
@end
在我的 TableView 委托(delegate)中,我添加了一个选择器,如果切换状态翻转,则会调用该选择器:
- (UITableViewCell *) tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat: @"%d:%d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]];
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
switch (indexPath.section) {
case(kMyFirstSection): {
switch (indexPath.row) {
case(kMyFirstSectionFirstRow) {
[cellOwner loadMyNibFile:@"RootLabeledSwitchTableCell"];
cell = (RootLabeledSwitchTableCell *)cellOwner.cell;
self.keychainSwitch = [(RootLabeledSwitchTableCell *)cell labeledSwitch];
[self.keychainSwitch addTarget:self action:@selector(keychainOptionSwitched) forControlEvents:UIControlEventValueChanged];
break;
}
// ...
}
}
// ...
}
}
所以这个选择器可以正常工作:
- (void) keychainOptionSwitched {
NSLog(@"Switched keychain option from %d to %d", ![self.keychainSwitch isOn], [self.keychainSwitch isOn]);
}
但是,我无法使用 UISwitch
实例的 -setOn:animated:
方法来初始化其初始状态:
- (void) updateInterfaceState {
BOOL isFirstTimeRun = [[[NSUserDefaults standardUserDefaults] objectForKey:kIsFirstTimeRunKey] boolValue];
if (isFirstTimeRun) {
[self.keychainSwitch setOn:NO animated:NO];
}
}
根据测试,self.keychainSwitch
为 nil
,这导致 -setOn:animated
不执行任何操作,但我仍然可以操作开关并且 NSLog
语句将正确打印开关状态更改,例如:
[Session started at 2009-08-24 07:04:56 -0700.]
2009-08-24 07:04:58.489 MyApp[29868:20b] keychain switch is: nil
2009-08-24 07:05:00.641 MyApp[29868:20b] Switched keychain option from 1 to 0
2009-08-24 07:05:01.536 MyApp[29868:20b] Switched keychain option from 0 to 1
2009-08-24 07:05:02.928 MyApp[29868:20b] Switched keychain option from 1 to 0
在 UITableView
委托(delegate)方法中设置 self.keychainSwitch
时,我是否遗漏了什么?
最佳答案
我花了很长时间摆弄带有简单标签的自定义 UITableViewCells 并打开它,然后才发现我可以添加一个 UISwitch 作为附件 View 。无论如何,您可能已经意识到这一点,并且出于其他原因需要自定义单元格,但以防万一我想提一下这一点!
您可以按如下方式执行此操作(在 -tableView:cellForRowAtIndexPath 方法中):
UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
cell.accessoryView = mySwitch;
accessoryView 位还负责调整大小和位置,因此我们可以摆脱 CGRectZero。
然后您就可以使用系统控制事件和 setOn 方法,如下所示(请注意,我们将其转换为我们知道的 UISwitch 指针):
[(UISwitch *)cell.accessoryView setOn:YES]; // Or NO, obviously!
[(UISwitch *)cell.accessoryView addTarget:self action:@selector(mySelector)
forControlEvents:UIControlEventValueChanged];
关于iphone - 自定义 UITableViewCell 内的 UISwitch 不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1322754/