2013-02-21 95 views
0

在我的應用程序中,我在表格視圖中添加了一個滑塊,即每行都包含一個滑塊&它也可以正常工作。Slider在Iphone SDK的表格視圖中重新加載

但是,當我滾動表視圖滑塊得到重新載入,即每個顯示我的起始位置,而不是滑塊值。

//My code is as follow for slider in table cell: 

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

    NSString *CellIdentifier=[NSString stringWithFormat:@"CellIdentifier%d",indexPath.row]; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 

    if (cell == nil) { 

     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; 

     return cell; 
    } 


    UISlider* theSlider = [[[UISlider alloc] initWithFrame:CGRectMake(174,12,120,23)] autorelease]; 
     theSlider.maximumValue=99; 
     theSlider.minimumValue=0; 
     [cell addSubview:theSlider]; 

return cell; 
} 

我該如何解決這個問題?

回答

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


NSString *CellIdentifier=[NSString stringWithFormat:@"CellIdentifier%d",indexPath.row]; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) { 

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; UISlider* theSlider = [[[UISlider alloc] initWithFrame:CGRectMake(174,12,120,23)] autorelease]; 
    theSlider.maximumValue=99; 
    theSlider.minimumValue=0; 
    [cell addSubview:theSlider]; 
} return cell; 

這樣滑塊被創建,只有當細胞是零即細胞被創建。並使用tableView:willDisplayCell:forRowAtIndexPath:方法來設置滑塊值,如slider.value = yourvalue;

+0

感謝您的回覆!但我的表視圖或它不顯示任何與此代碼的行。 – user1673099 2013-02-21 11:32:15

+0

我編輯了代碼。現在試試。 – Raj 2013-02-21 12:29:04

+0

非常感謝! – user1673099 2013-02-21 12:49:35

2

您需要存儲滑塊觀的價值和問題是cellForRowAtIndexPath被稱爲不只是一次設置sliderview的值cellForRowAtIndexPathslider.value = yourvalue;

1

,但每次在的tableView需要渲染單元時間..所以你必須確保只有初始化theSlider第一次叫...

最好的方法是定義一個定製UITableViewCell,並把那裏將存儲theSlider,那麼,當cellForRowAtIndexPath被調用,檢查屬性如果它已經被初始化,請參閱:

// If the slider is not yet initialized, then do it 
if(cell.theSlider == nil) 
{ 
    // Init... 
} 
+0

你可以發佈一些更多的代碼,因爲如何在方法中編寫'cell.theSlider'? – user1673099 2013-02-21 11:27:33

+0

你必須先創建一個自定義的UITableViewCell,在故事板中設置它,拖動滑塊並將它作爲IBOutlet鏈接到你的自定義UITableViewCell,然後...你將擁有cell.theSlider屬性。 選中此:http://www.appcoda.com/customize-table-view-cells-for-uitableview/ – apascual 2013-02-21 11:35:37

1

這實在是來自「cellForRowAtIndexPath」的方法。每當您滾動時,每個單元格都會變得nil並重新初始化它。更好的方法是嘗試創建自定義單元格類(BY創建UITableViewCell的子類)以及條件爲「if (cell == nil)」的定義滑塊。

相關問題