Как добавить кнопку на определенную ячейку в табличном представлении. Когда я попытался это отобразить во всех ячейках
Текстура показывает мой вопрос. Я хочу добавить кнопку только во 2-ю и 5-ю ячейки. И как я могу это сделать?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.row == 2 || indexPath.row == 5) {
// here button creation code
}
}
Когда он запускается первый раз, он отображается в определенной ячейке, но после прокрутки отображается во всех ячейках в табличном представлении.
Заранее спасибо.
2 ответа
Это будет хорошо работать:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
// here is the redbutton
if indexPath.row == 2 || indexPath.row == 5{
var redBtn = UIButton()
redBtn = UIButton(frame: CGRectMake(0, 0, 40, 40))
redBtn.backgroundColor = UIColor.redColor()
cell.addSubview(redBtn)
}
//label text just added from an array
cell.textLabel?.textAlignment = NSTextAlignment.Center
cell.textLabel?.text = items[indexPath.row]
return cell
}
Поместите условие в ячейку для строки в indexpath:
если indexPath.row
== somevalue тогда:
var button=UIButton(frame: CGRectMake(150, 240, 75, 30))
button.setTitle("Next", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
button.tag = 1010
button.backgroundColor = UIColor.greenColor()
cell.contentView.addSubview(button)
Просто удалите кнопку из ячейки в другой части:
cell.contentView.viewWithTag(1010).removeFromSuperview()