Reputation: 295
I have a program that adds a new cell for every new song that is played. For example if a song is playing, the program will list that information in a cell but as soon as the song changes the new song's information will be added to a new cell, but I also want a button to be added for every new cell. How do I do that? below is what I have tried so far.
// ...
playButton = UIButton()
let imageret = "playbutton"
playButton.setImage(UIImage(named: imageret), forState: .Normal)
}
func play(sender: UIButton){
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = self.table.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
var play: Play
playButton.tag = indexPath.row
playButton.addTarget(self,action: "play:", forControlEvents: UIControlEvents.TouchUpInside)
table.addSubview(playButton)
// ...
Upvotes: 1
Views: 4318
Reputation: 11201
you can try this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
let button : UIButton = UIButton(type: UIButton.ButtonType.custom) as UIButton
button.frame = CGRect(x: 40, y: 60, width: 100, height: 24)
button.addTarget(self, action: "playButton:", for: UIControl.Event.touchUpInside)
button.setTitle("Click Me !", for: .normal)
//Remove all subviews so the button isn't added twice when reusing the cell.
for view: UIView in cell.contentView.subviews as! Array<UIView> {
view.removeFromSuperview()
}
cell.contentView.addSubview(button)
return cell;
}
Upvotes: 1