【发布时间】:2015-10-22 08:29:30
【问题描述】:
我正在做一个 swift 项目,我有一个包含 3 个单元格的表格视图,我想删除第三个单元格中的所有按钮并在有人单击第二个单元格上的任何按钮时插入新按钮,代码如下这个
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: DateTableViewCell!
if indexPath.row == 0 {
// First row code goes here
} else if indexPath.row == 1 {
for index in 0...6 {
var button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as!UIButton
button.frame = CGRectMake(CGFloat(intXTile), CGFloat(28), CGFloat(40), CGFloat(30))
button.setTitle("Button Title", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)
cell.addSubview(button)
}
} else if indexPath.row == 2 {
// Third row code goes here
}
}
func buttonClicked(sender: UIButton!) {
var btn:UIButton = sender
let subviews = sender.superview?.superview?.subviews as! [UIView]
for aSubview in self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))!.contentView.subviews {
if aSubview is UIButton {
aSubview.removeFromSuperview()
}
var answerText: Array<String?> = ["Button5","Button6","Button7","Button8"]
var answerButton: Array<UIButton> = []
for var i = 0; i<=answerText.count; i++ {
var button = UIButton.buttonWithType(.System) as! UIButton
button.titleLabel!.font = UIFont.systemFontOfSize(12)
button.titleLabel!.lineBreakMode = .ByTruncatingTail
var numberOfButton = 5
let j = i
var y:CGFloat = (CGFloat)(j*290/(numberOfButton+1)-1);
button.frame.size.height = 30
button.frame.size.width = 200
button.frame.origin.y = y
button.frame.origin.x = 50.0
answerButton .insert(button, atIndex: i)
}
for var i = 0; i<answerText.count; i++ {
var button:UIButton = answerButton [i]
button.setTitle(answerText[i], forState: UIControlState.Normal)
aSubview.addSubview(button)
}
}
}
Story Board 中的数据表视图控制器场景是这样的
当点击任何第二个单元格按钮时,将调用“buttonClicked”方法,我需要删除并使用新数据更新按钮,现在它向第三个单元格添加新按钮,但不会删除现有的按钮,我还需要将按钮正确放置在第三个单元格中,从过去 2 天开始我一直在努力完成这项工作,有人可以帮我解决这个问题,非常感谢。
【问题讨论】:
-
我使用的是动态原型,有 3 个原型单元
-
您应该在更改单元格内容数据时重新加载表格视图或具体单元格。要获取单元格,您应该通过 indexpath 或标签调用它
-
谢谢,你能指导我怎么做吗?