还有一个同样逻辑的问题。选择单元格时 UITableViewCell 子视图消失 https://stackoverflow.com/questions/6745919/uitableviewcell-subview-disappears-when-cell-is-selectedBut我没有得到我想要的正确解决方案。他们建议像这样子类化视图。但我需要在单元格本身内显示按钮。
让我们来回答我的问题:
我有一个定制的、以编程方式创建的表格视图。
请看一下屏幕截图。
在此,我以编程方式将按钮添加到表格视图单元格中。
让我们来解决这个问题。
当我选择任何单元格时,它也会隐藏该按钮,我想看到该按钮。
我的代码在这里:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
// here is the redbutton
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 创建代码:
var tableView: UITableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = CGRectMake(0, 50, self.view.frame.width,self.view.frame.height);
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 30
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
}
提前致谢。
这是一个解决方案。为按钮指定一个标签号。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
// here is the redbutton
var redBtn = UIButton()
redBtn = UIButton(frame: CGRectMake(0, 0, 40, 40))
redBtn.backgroundColor = UIColor.redColor()
cell.contentView.addSubview(redBtn)
redBtn.tag = 101
//label text just added from an array
cell.textLabel?.textAlignment = NSTextAlignment.Center
cell.textLabel?.text = items[indexPath.row]
return cell
}
现在在 didSelectRowAt Index 方法中添加这个。
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
var selectedCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!
for subViews in selectedCell.contentView.subviews {
if subViews is UIButton && subViews.tag == 101 {
let button = subViews as! UIButton
selectedCell.bringSubviewToFront(button)
button.backgroundColor = UIColor.redColor()
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)