我有一个程序可以为每首新歌添加一个新单元格。例如,如果正在播放歌曲,程序将在单元格中列出该信息,但是一旦歌曲改变,新歌曲的信息将被添加到新单元格中,但我还想要添加一个按钮用于每个新细胞。我怎么做?以下是我到目前为止所尝试的内容。
// ...
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)
// ...
答案 0 :(得分:1)
你可以试试这个:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
let button : UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button.frame = CGRectMake(40, 60, 100, 24)
button.addTarget(self, action: "playButton:", forControlEvents: UIControlEvents.TouchUpInside)
button.setTitle("Click Me !", forState: UIControlState.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;
}