2011-04-03 76 views
1

我想要在iphone應用程序中使用切換開關來設置某些功能的開啓或關閉。我看過教程,但他們只展示瞭如何在iPhone的設置位置執行此操作。我希望在應用程序內完成此操作。任何指南,幫助建議。我正在尋找類似於下面的圖片。iPhone和應用程序設置

enter image description here

回答

2

您可以將UISwitch用作accessoryView。這將看起來(幾乎?)完全像你的照片。

事情是這樣的:

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"CellIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (!cell) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
     UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease]; 
     [mySwitch addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged]; 
     cell.accessoryView = mySwitch; 
    } 
    // configure cell 
    UISwitch *mySwitch = (UISwitch *)cell.accessoryView; 
    mySwitch.on = YES; // or NO 
    cell.textLabel.text = @"Auto Connect"; 

    return cell; 
} 

- (IBAction)switchToggled:(UISwitch *)sender { 
    UITableViewCell *cell = (UITableViewCell *)[sender superview]; 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
    NSLog(@"Switch %i,%i toggled", indexPath.section, indexPath.row); 
} 
1

可以使用UISwitch。這是非常簡單的課程參考指南。

http://developer.apple.com/library/ios/#documentation/uikit/reference/UISwitch_Class/Reference/Reference.html

基本上,你可以通過查看它的「關於」財產檢查其狀態。

if(mySwitch.on) { 
    //do something here 
} 
+0

是的,但我的努力得到它的表內,或者至少這就是它看起來是,由圖像 – Vikings 2011-04-03 05:00:39

+0

的UISwitch的外觀只是一個UIView子類,所以您可以將此視圖添加到自定義tableView單元格。取決於你想在你的tableView中添加它的位置取決於你如何將它設計到你的代碼中。 – Jamie 2011-04-03 05:12:26

1

首先,確保你的UITableView樣式設置爲 「分組」

然後,在你的cellForRowAtIndexPath方法,做一些沿着這些線路:

if (indexPath.section == kSwitchSection) { 


    if (!randomControl) { 
     randomControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ]; 
     [randomControl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged]; 
     randomLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,8,180,30)]; 
     [randomLabel setFont:[UIFont boldSystemFontOfSize:16]]; 
     [randomLabel setText:@"My Label"]; 
    } 

    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    [cell addSubview:randomControl]; 
    [cell addSubview:randomLabel]; 
} 

記住釋放UISwitch對象,幷包含用於將其設置爲打開或關閉的代碼,具體取決於它應處於的狀態。