Tableview 选择将我的按钮隐藏在 tableview 单元格中 [英] Tableview selection hides my button within the tableview cell
问题描述
还有一个逻辑相同的问题.UITableViewCell子视图在单元格被选中时消失 我没有得到我想要的正确解决方案.他们建议像这样子类化视图.但我需要在单元格本身内显示按钮.
There is another question with same logic.UITableViewCell subview disappears when cell is selected i did not get correct solution which i want.They suggest to subclass view like that.But i need display button within the cell itself.
让我们来回答我的问题:
Lets come to my question:
我有一个自定义并以编程方式创建的 tableview.
I have a customized and programmatically created tableview.
请看截图.
在这里,我以编程方式向 tableview 单元格添加了按钮.
In this i added button programmatically to the tableview cell.
让我们来解决这个问题.
Lets come to the problem.
当我选择任何单元格时,它也会隐藏按钮,我想看到该按钮.
When i select any cell it hides the button also,I want to visible that button.
我的代码在这里:
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 创建代码:
If need : Tableview creation code:
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)
}
提前致谢.
推荐答案
这里有一个解决方案.给按钮一个标签编号.
Here is a solution. Give a tag number to the button.
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
}
现在在 didSelectRowAtIndex 方法中添加这个.
Now in didSelectRowAtIndex method add this.
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()
}
}
}
这篇关于Tableview 选择将我的按钮隐藏在 tableview 单元格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!