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

标签 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

}

最佳答案

将此代码用于 Swift 4 或 5

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

关于ios - 如何以编程方式更改 UIButton 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31616341/

相关文章:

iphone - ScrollView iPhone 内的文本字段

iphone - 在 iphone 应用程序中安装的设置 View

ios - 从 Swift 函数中的异步调用返回数据

ios - 在 Swift 中读取嵌套数组的正确语法?

swift - 用于在管道结果时链接异步操作的 GCD 模式

ios - 如何解释 Fabric 崩溃和 Xcode 崩溃之间的巨大差异?

ios - 带有静态枚举和字典的常量文件

ios - 为什么 Swift 的字符类型不是 Hashable?

xcode - Swift:(倒计时应用)如何让日期选择器选择截止日期?

ios - 在 Xcode 项目中组织文件并以编程方式获取文件夹列表