2013-12-08 45 views
0

嗨,我意識到這個問題之前已被問過。不幸的是,我嘗試了以前的解決方案,但無濟於事。我想要做的是讓我的UISwitch出現,而不是在滾動表格視圖時自我複製。這是我當前的嘗試,但UISwitch根本沒有顯示出來。任何幫助,我做錯了什麼將不勝感激!表查看元素的複製

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *simpleTableIdentifier = @"RestaurantCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 

    if (!cell) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; 
    } 

    Restaurant *restaurant = [restaurants objectAtIndex:indexPath.row]; 

    UISwitch *notificationSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(245, 15, 79, 27)]; 
    [notificationSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged]; 
    [cell.contentView addSubview:notificationSwitch]; 

    cell.textLabel.text = restaurant.name; 
    cell.detailTextLabel.text = restaurant.hours; 
    return cell; 
} 

回答

0

嘗試使用此代碼,而不是我的靜態文本,你會把你的text.It爲我工作!

You can see the structure of cell Attached Image

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    static NSString *cellIdentifier = @"CellIdentifer"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    if (!cell) { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; 

    } 

    UISwitch *notificationSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(150, 5, 79, 27)]; 
    [notificationSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged]; 
    [cell.contentView addSubview:notificationSwitch]; 

    cell.textLabel.text = [NSString stringWithFormat:@"text label %d",indexPath.row]; 
    cell.detailTextLabel.text =[NSString stringWithFormat:@"detail label %d",indexPath.row] ; 
    return cell; 

} 
+0

我該怎麼辦?我是新來的!對不起:( – Inovize

+0

@Inovize:你可以嘗試我編輯的代碼,它的工作原理。 – ManiaChamp

1

我所試圖做的是讓我的UISwitch出現,並在表視圖滾動時

看來你想要一個UISwitch不重複自己出現在所有的細胞中。
要解決此問題,請不要在-cellForRowAtIndexPath中創建對象,而應將此代碼移動到-viewDidLoad中,並稍後將此對象放在可重新使用的單元格中。


基本上...
這應該是你的-viewDidLoad

//IMPORTANT: declare "UISwitch *notificationSwitch;" in the .h of this class 
notificationSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(245, 15, 79, 27)]; 
[notificationSwitch addTarget:self 
         action:@selector(switchChanged:) 
      forControlEvents:UIControlEventValueChanged]; 

只有這應該在-cellForRowAtIndexPath

[cell.contentView addSubview:notificationSwitch]; 

留因此,我們創建只對象一次,並將相同的對象添加到單元格multi PLE倍,而不是在-cellForRowAtIndexPath創建多個對象(,只有看起來是一樣的,但INFACT不同的對象


PS:我認爲您的委託和數據源都連接正確,即執行流量達到-cellForRowAtIndexPath