2015-09-12 215 views
0

我有一個程序爲播放的每首新歌添加一個新的單元格。例如,如果一首歌曲正在播放,程序將在單元格中列出該信息,但只要歌曲發生變化,新歌曲的信息將被添加到新單元格中,但我還希望爲每個新單元格添加一個按鈕。我怎麼做?以下是我迄今爲止所嘗試的內容。如何將按鈕添加到uitableview的每個單元格?

// ... 

    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

將它編程? –

+0

是的,我想以編程方式添加它 – blee

+1

更好的選擇是將按鈕添加到故事板中的原型單元格。然後你可以將按鈕的「play:」動作連接到你的單元格的子類。 –

回答

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

這段代碼有幾個問題。隨着單元重複使用,該代碼不斷向單元添加越來越多的按鈕。確保只有一個按鈕被添加到單元格中。按鈕(或任何子視圖)應該總是添加到單元格的「contentView」中,而不是直接添加到單元格中。 – rmaddy

+0

@ lucaslt89盲目刪除所有子視圖是一個壞主意。爲什麼不簡單地重用任何現有的按鈕而不是銷燬單元格的內容?順便說一句 - 這不是一個適當的編輯別人的答案。 – rmaddy

+1

用戶要求以編程方式添加按鈕,所以我假定該按鈕是單元格中唯一的組件。我不想創建一個新的答案,因爲這是正確的,只是有一些問題,我通過編輯來解決。版本經歷審查過程,所以在這種情況下,編輯幾乎正確的答案是一個好主意 – lucaslt89

相關問題