2014-01-26 89 views
1

我有一個表視圖與三個表視圖單元格。 在單元配置期間,我將UITextField添加到每個單元格,並且還在所有文本字段上設置了佔位符值。 當表視圖加載最終的結果是這樣的:UITextField佔位符文本覆蓋問題

Table view after load

我遇到的問題是,當我繼續滾動細胞「關閉屏幕」,當他們再次出現佔位符文本得到越來越暗,就像這裏:

Darker placeholder text

當我再嘗試通過鍵入一個名稱改變的UITextField的字符串值,或通過在最後一個單元編程改變佔位符值,這些屬性的舊值停留,和新的價值被覆蓋在細胞中,像這樣:

enter image description here

這裏是負責配置這些細胞的方法:

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

    // Configure the cell... 
    [self configureCell:cell forIndexPath:indexPath]; 

    return cell; 
} 

- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath 
{ 
    for (UIView *subview in cell.contentView.subviews) { 
     [subview removeFromSuperview]; 
    } 

    cell.backgroundColor = [UIColor whiteColor]; 
    cell.autoresizesSubviews = YES; 
    cell.clearsContextBeforeDrawing = YES; 
    CGRect textFieldFrame = cell.bounds; 
    textFieldFrame.origin.x += 10; 
    textFieldFrame.size.width -= 10; 

    UITextField *textField = [[UITextField alloc] initWithFrame:textFieldFrame]; 
    textField.adjustsFontSizeToFitWidth = YES; 
    textField.textColor = [UIColor lightGrayColor]; 
    textField.enabled = YES; 
    textField.userInteractionEnabled = NO; 
    textField.autoresizingMask = UIViewAutoresizingFlexibleWidth; 
    textField.clearsContextBeforeDrawing = YES; 
    textField.clearsOnBeginEditing = YES; 

    if (indexPath.section == ATTAddNewTimerSectionName) { 
     textField.placeholder = @"Name"; 
     textField.userInteractionEnabled = YES; 
     textField.delegate = self; 
     textField.returnKeyType = UIReturnKeyDone; 
     textField.clearButtonMode = UITextFieldViewModeWhileEditing; 
    } else if (indexPath.section == ATTAddNewTimerSectionDate) { 
     textField.placeholder = @"Date/Time"; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } else if (indexPath.section == ATTAddNewTimerSectionCalendar) { 
     if (self.userCalendarEvent == nil) { 
      textField.placeholder = @"See list of calendar events"; 
     } else { 
      textField.placeholder = nil; 
      textField.placeholder = self.userCalendarEvent.title; 
     } 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } 
    [cell addSubview:textField]; 
} 

正如你所看到的,我曾嘗試過各種東西,比如刪除所有在向單元格或設置添加新視圖之前的子視圖 - 單元格和UITextView上的[UIView setClearsContextBeforeDrawing:YES],甚至將佔位符值設置爲零,但沒有成功。

任何指針將不勝感激!

回答

2

你正在製造一個很多人都會犯的經典錯誤。在滾動表格時,單元格會被重用。

正如您所寫,每次使用單元格時,您的代碼都會不斷創建並添加新的文本字段。所以你看到了單元格中有多個文本字段的結果。

您只想將一個文本字段添加到單元格中。更新您的代碼,以便只添加文本字段,如果它不存在。

看來你在代碼中存在邏輯問題。您直接將文本字段添加到單元格,但您嘗試從單元格的contentView中刪除它。

更改此:

[cell addSubview:textField]; 

到:

​​
+0

是的,這就是問題所在。如果您看到文本與佔位符重疊,則可能是因爲在同一位置有> = 2個UITextFields – onmyway133