1

I have a button on custom tableviewcell. I've been able add action to this button by add target like below code:

    var playButton = cell.contentView.viewWithTag(5) as? UIButton
    var sender : UIButton = UIButton()
    playButton?.addTarget(self, action: "playPost:", forControlEvents: UIControlEvents.TouchUpInside)
    playButton?.layer.setValue(object["previewUrl"] as? String, forKey: "songUrl")
    playButton?.layer.setValue(indexPath.row, forKey: "index")

But, how can I change it's title whenever I clicked this button?

Ega Setya Putra
  • 1,645
  • 6
  • 23
  • 51

2 Answers2

0

If your function is playPost(), you could change the value passed in (which is the sender of the function, by default) like this:

func playPost(sender: UIButton) {

    sender.setTitle("New title", forState: UIControlState.Normal);
}
rebello95
  • 8,486
  • 5
  • 44
  • 65
  • thank you very much, this is what I looking for. Is it possible to change other element title on the same cell? – Ega Setya Putra Jun 17 '15 at 04:59
  • @EgaSetyaPutra Yes you could. I'd set the `tag` of the button to the cell's `row`, then call `cellForRowAtIndexPath:`, constructing the index path using the button's tag. Make sense? – rebello95 Jun 17 '15 at 05:03
  • I don't get it, could you give some reference or code snippet? – Ega Setya Putra Jun 17 '15 at 05:08
  • @EgaSetyaPutra Here's another way to do it, which may be better: http://stackoverflow.com/a/16270198/1145804 Please note that this is not pertinent to the original question you posted, so if my answer helps, please accept it. If this linked thread doesn't help answer your other question, please post a new one. – rebello95 Jun 17 '15 at 05:10
  • ok, thanks for your suggestion. I think I'm gonna make another post – Ega Setya Putra Jun 17 '15 at 05:18
0

You can Change UIButton title by using setTitle Method

Example

    var button = UIButton(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
    button.backgroundColor = UIColor.blackColor()
    button.setTitle("Start", forState: UIControlState.Normal)
    button.addTarget(self, action: "pressButton:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(button)


   func pressButton(sender:UIButton)
   {
      if sender.titleLabel?.text == "Start"
      {
        sender.setTitle("Stop", forState: UIControlState.Normal)
      }
      else
      {
        sender.setTitle("Start", forState: UIControlState.Normal)
      }
   }
iDhaval
  • 3,175
  • 1
  • 11
  • 21