【发布时间】:2010-08-26 19:19:17
【问题描述】:
警告:我已经找到了我的问题的答案,有几个已经接近了,但我仍然缺少一些东西。这是场景:
我想要一种在运行时根据表中的数据动态创建包含UISwitches 的UITableViewCells 的方法(我可以这样做)。问题在于连接开关,以便在更改视图(导航离开、关闭等)时我可以获得它们的值。我试图使用事件UIControlEventValueChanged 来获得通知,但未能正确指定它,因为当点击该开关时它会转储。此外,似乎没有任何方法可以唯一标识开关,因此如果所有事件都由单个例程处理(理想情况),我无法区分它们。
所以...
如果我有一个 UITableView:
@interface RootViewController : UITableViewController
{
UISwitch * autoLockSwitch;
}
@property (nonatomic, retain) UISwitch * autoLockSwitch;
-(void) switchFlipState: (id) sender;
@end
// .m 文件:
@implementation RootViewController
// ...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = @"Cell";
int row = 0;
NSString * label = nil;
TableCellDef_t * cell_def = nil;
row = indexPath.row;
cell_def = &mainMenuTableCellsDef[ row ];
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
label = (NSString *) mainMenuTableCellsDef[indexPath.row].text;
[cell.textLabel setText:(NSString *) mainMenuItemStrings[ indexPath.row ]];
if (cell_def->isSpecial) // call special func/method to add switch et al to cell.
{
(*cell_def->isSpecial)(cell ); // add switch, button, etc.
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
}
and this is the 'special' function:
-(void) autoLockSpecialItem :(UITableViewCell *) cell
{
autoLockSwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
[autoLockSwitch addTarget:self action:@selector(switchFlipState:) forControlEvents:UIControlEventValueChanged ];
[cell addSubview:autoLockSwitch];
cell.accessoryView = autoLockSwitch;
}
最后:
-(void) switchFlipState: (id) sender
{
NSLog(@"FLIPPED");
}
================================================ ===============
问题:
为什么当开关被点击时它会崩溃(错误的选择器)?我相信我的代码遵循了我见过的所有示例代码,但显然有问题。
我无法将实例方法作为函数指针放入表中;而且它似乎也不喜欢类方法。如果我将其设为“C/C++”函数,如何访问类/实例成员变量?也就是说,如果我想将对
autoLockSpecialItem的调用放入静态表(或合理的传真)中,以便我可以获得autoLockSwitch成员变量?如果我将其设为类方法并将autoLockSwitchvar 设为静态,那是否有效?更简单地说:如何将
UIControlEventValueChanged连接到我的视图(我尝试过但失败了),我能否在运行时在事件处理程序中区分哪个开关已更改?有没有更好的方法?我不敢相信我是第一个必须解决这类问题的人。
抱歉,感谢您的关注,感谢您提供的任何和所有帮助。
:bp:
【问题讨论】:
标签: iphone objective-c uitableview ios4 uiswitch