简体   繁体   中英

How do I add a button to each cell of the uitableview?

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)

    // ...

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;   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM