如何在UITableView
單元上嵌入UISwitch
?示例可以在設置菜單中看到。UITableView單元中的UISwitch
我目前的解決方案:
UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease];
cell.accessoryView = mySwitch;
如何在UITableView
單元上嵌入UISwitch
?示例可以在設置菜單中看到。UITableView單元中的UISwitch
我目前的解決方案:
UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease];
cell.accessoryView = mySwitch;
將其設置爲accessoryView通常是要走的路。您可以在tableView:cellForRowAtIndexPath:
中進行設置您可能希望在切換開關時使用目標/操作來執行某些操作。像這樣:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
switch([indexPath row]) {
case MY_SWITCH_CELL: {
UITableViewCell *aCell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"];
if(aCell == nil) {
aCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease];
aCell.textLabel.text = @"I Have A Switch";
aCell.selectionStyle = UITableViewCellSelectionStyleNone;
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
aCell.accessoryView = switchView;
[switchView setOn:NO animated:NO];
[switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[switchView release];
}
return aCell;
}
break;
}
return nil;
}
- (void)switchChanged:(id)sender {
UISwitch *switchControl = sender;
NSLog(@"The switch is %@", switchControl.on ? @"ON" : @"OFF");
}
您可以添加UISwitch或任何其他控制單元的accessoryView
。這樣它會出現在單元格的右側,這可能是你想要的。
您可以在Interfacebuilder中準備單元格,將其鏈接到ViewController的IBOutlet,並在tableview要求正確的行時將其返回。
相反,您可以爲單元格創建一個單獨的xib(再次使用IB),並在創建單元格時使用UINib加載它。
最後,您可以通過編程方式創建開關並將其添加到您的單元格contentview或accessoryview。
哪一個最適合你,主要取決於你喜歡做什麼。如果你的桌面內容是固定的(對於設置頁面等),前兩個可能工作得很好,如果內容是動態的,我更喜歡編程解決方案。請更具體地說明你想做什麼,這會讓你更容易回答你的問題。
我更喜歡編程解決方案(儘管它是設置頁面),但我也對前兩個選項的工作方式感興趣。也許你可以更詳細地解釋一下它們。 – testing 2010-09-22 17:11:34
if (indexPath.row == 0) {//If you want UISwitch on particular row
UISwitch *theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[cell addSubview:theSwitch];
cell.accessoryView = theSwitch;
}
你目前的做法有什麼問題嗎? – MobileMon 2013-08-26 15:14:05