如何以编程方式更改UIButton标签

时间:2015-07-24 17:23:01

标签: ios xcode swift uibutton

当我第一次运行我的应用程序时,我从服务器检索一个数字并将其显示为我的UIButton标签。可以将其视为红色UIButton上显示的通知编号。

当我在应用程序中删除通知时,我希望我的UIButton标签减1。我可以在删除通知后从服务器获取减少的数字,但我无法显示此新数字UIButton。该按钮始终显示首次触发应用程序时的编号。

我删除通知以更新UIButton后调用makeButtonView()方法

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

}

6 个答案:

答案 0 :(得分:1)

我需要更多信息才能为您提供正确的代码。但这种方法应该有效:

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

答案 1 :(得分:1)

There have been some updates since Swift 4. This works for me:

self.button.setTitle("Button Title", for: UIControl.State.init(rawValue: 0))

Replace button with your IBOutlet name. You can also use a variable or array in place of the quoted text.

答案 2 :(得分:0)

这很简单......

import UIKit

class ViewController: UIViewController {

    @IBOutlet var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        button.setTitle("hello world", forState: UIControlState.Normal)
    }
}

我相信如果你将状态设置为正常,只要你没有为这些状态明确设置标题,该值就会默认传播到其他状态。

换句话说,如果将其设置为正常,则当按钮进入其他状态时,它也应显示此标题

UIControlState.allZeros
UIControlState.Application
UIControlState.Disabled
UIControlState.Highlighted
UIControlState.Reserved
UIControlState.Selected

最后,如果您有其他问题,请访问this post

答案 3 :(得分:0)

Use this code for Swift 4 or 5

button.setTitle("Click Me", for: .normal)

答案 4 :(得分:0)

Since your API call should be running on a background thread you need to dispatch your UI update back to the main thread like this:

DispatchQueue.main.async {
      button.setTitle(“new value”, forState: .normal)
  }

答案 5 :(得分:0)

设置标题后,只需简单地重绘按钮即可:

button.setNeedsDisplay();