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

问题描述 投票:0回答:5

当我第一次运行我的应用程序时,我从服务器检索一个数字并显示它为我的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

}
ios xcode swift uibutton
5个回答
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
投票

自Swift 4以来有一些更新。这对我有用:

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

用您的IBOutlet名称替换按钮。您还可以使用变量或数组代替引用的文本。


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

最后,如果你有其他问题,这里是Apple's documentation


0
投票

将此代码用于Swift 4或5

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

0
投票

由于您的API调用应该在后台线程上运行,您需要将UI更新分发回主线程,如下所示:

DispatchQueue.main.async {
      button.setTitle(“new value”, forState: .normal)
  }
© www.soinside.com 2019 - 2024. All rights reserved.