我希望表的第一行有一个带有TextField的单元格(在我的例子中名为FindTextField)。我实现的方式(见下面的代码),因为单元格被重用,如果单元格列表向下滚动,那么更多的单元格将被分配TextField。我想知道如何使用标签或其他任何允许强制只有第一行具有TextField的东西,即使用户一直向下滚动,然后向上滚动。
现在,这是代码:
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("identifier",
forIndexPath: indexPath) as UITableViewCell
if indexPath.row == 0 {
FindTextField.frame = CGRectMake(74, 4, cell.bounds.width - 78 , cell.bounds.height - 8)
FindTextField.hidden = false
FindTextField.placeholder = "Find"
FindTextField.font = UIFont.systemFontOfSize(20)
FindTextField.borderStyle = UITextBorderStyle.RoundedRect
FindTextField.autocorrectionType = UITextAutocorrectionType.No
FindTextField.keyboardType = UIKeyboardType.Default
FindTextField.returnKeyType = UIReturnKeyType.Done
FindTextField.clearButtonMode = UITextFieldViewMode.WhileEditing;
FindTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
FindTextField.delegate = self
FindTextField.autocapitalizationType = .AllCharacters
cell.contentView.addSubview(FindTextField)
cell.imageView?.image = UIImage(named: "menu_find.png")
cell.textLabel?.hidden = true
}
cell.textLabel!.text = StationsChatList[indexPath.row]
cell.textLabel!.font = UIFont.systemFontOfSize(24)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.backgroundColor = UIColor.blackColor()
cell.backgroundColor = UIColor.blackColor()
cell.layer.borderWidth = 1.0
cell.layer.borderColor = UIColor.darkGrayColor().CGColor
return cell
}
您可以将tag
分配给textField
,然后访问它。当row != 0
时,只需隐藏它。这就是我所说的:
if cell.viewWithTag(1001) == nil { // init your text field
FindTextField.frame = ...
FindTextField.tag = 1001 // or whatever you want
...
}
cell.viewWithTag(1001)?.hidden = indexPath.row != 0
...
还有另一种方法-在单元格中实现prepareForReuse()
方法,并手动隐藏FindTextField
(它将为每个单元格隐藏)。稍后在cellForRow
内部使其在row == 0
中可见。