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:
I have a customized and programmatically created tableview.
Please take a look at the screenshots.
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.
My code here :
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
}
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)
}
Thanks In Advance.
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
}
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()
}
}
}