Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change UIButton label programmatically

When I first run my app, I retrieve a number from my server and display it for my UIButton label. Think of this as a notification number displayed on a red UIButton.

When I remove a notification within the app, I want my UIButton label decrement by 1. I am able to get the decremented number from the server after I delete a notification, but I can't display this new number on the UIButton. The button always displays the number when the app is first fired.

I call makeButtonView() method after I remove a notification to update the UIButton

func makeButtonView(){
    var button = makeButton()
    view.addSubView(button)

    button.tag = 2
    if (view.viewWithTag(2) != nil) {
        view.viewWithTag(2)?.removeFromSuperview()
        var updatedButton = makeButton()
        view.addSubview(updatedButton)
    }else{
        println("No button found with tag 2")
    }


}

func makeButton() -> UIButton{
 let button = UIButton(frame: CGRectMake(50, 5, 60, 40))
 button.setBackgroundImage(UIImage(named: "redBubbleButton"), forState: .Normal)
    API.getNotificationCount(userID) {
        data, error in

        button.setTitle("\(data)", forState: UIControlState.Normal)

    }
    button.addTarget(self, action: "targetController:", forControlEvents: UIControlEvents.TouchUpInside)

    return button

}
like image 832
Kleinfeltersville Avatar asked Jan 28 '26 12:01

Kleinfeltersville


2 Answers

Use this code for Swift 4 or 5

button.setTitle("Click Me", for: .normal)
like image 192
AtulParmar Avatar answered Jan 30 '26 01:01

AtulParmar


I need more information to give you a proper code. But this approach should work:

lazy var button : UIButton = {
    let button = UIButton(frame: CGRectMake(50, 5, 60, 40))
    button.setBackgroundImage(UIImage(named: "redBubbleButton"), forState: .Normal)
    button.addTarget(self, action: "targetController:", forControlEvents: UIControlEvents.TouchUpInside)

    return button
    }()

func makeButtonView(){
    // This should be called just once!!
    // Likely you should call this method from viewDidLoad()
    self.view.addSubview(button)
}

func updateButton(){
    API.getNotificationCount(userID) {
        data, error in
        // be sure this is call in the main thread!!
        button.setTitle("\(data)", forState: UIControlState.Normal)
    }
}
like image 44
agy Avatar answered Jan 30 '26 02:01

agy