Uitableview 如何在tableview中的特定单元格上添加按钮。当我尝试在所有单元格中显示该按钮时
小标题显示了我的问题。我只想在第2个和第5个单元格上添加按钮。我如何才能做到这一点Uitableview 如何在tableview中的特定单元格上添加按钮。当我尝试在所有单元格中显示该按钮时,uitableview,swift,uibutton,tableviewcell,Uitableview,Swift,Uibutton,Tableviewcell,小标题显示了我的问题。我只想在第2个和第5个单元格上添加按钮。我如何才能做到这一点 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if (indexPath.row == 2 || indexPath.row == 5) { // here button creati
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.row == 2 || indexPath.row == 5) {
// here button creation code
}
}
当它第一次运行时,它会显示在特定的单元格中,但在滚动之后,它会显示在tableview中的所有单元格中
提前感谢。在单元格中为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)
只需从else部分的单元格中删除按钮:
cell.contentView.viewWithTag(1010).removeFromSuperview()
这很好:
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
}
通过编码,你试过什么?我没有否决你的问题。我已经试过了。但是当滚动或选择时,按钮显示在每个单元格上是的,我想在我的其他代码中出错会检查谢谢我得到了问题只需将tableview高度设置为100,然后滚动即可看到问题使用自定义单元格检查我的更新项目: