UIButton setTitle 不起作用

UIButton setTitle doesn't work

我正在尝试更改 UIButton 被单击时的文本。我尝试了以下方法,但都失败了:

首先我尝试在故事板上插入一个按钮并将其链接到视图控制器,按钮的代码如下所示:

@IBAction func button(sender: AnyObject) {}. 

在按钮的括号内,我使用了

button.setTitle ("something" , for State: .Selected)

然而,当我在模拟器中运行这段代码时,它似乎根本不起作用。

我也试过,按照苹果参考手册,在点击上述按钮后,在侧边菜单中为不同的状态设置不同的标签,但仍然没有用。 任何人都可以确切地告诉我(即要编写什么代码以及代码的确切位置)如何实现这一目标吗?

创建IBAction函数时,sender的类型应该是UIButton。 发件人 是您的按钮。当您点击按钮时调用该函数。您必须在发件人(您的按钮)上使用函数 setTitle

@IBAction func buttonTouchedUpInside(sender: UIButton) { 
    sender.setTitle("buttonName", forState: .normal)
}

为您的按钮创建一个 IBOutlet,然后这段代码应该可以工作(假设您将 IBOutlet 命名为 button):

button.setTitle("title", forState: .Normal)
button.setTitle("title 1", forState: .Application)
button.setTitle("title 2", forState: .Highlighted)
button.setTitle("title 3", forState: .Reserved)
button.setTitle("title 4", forState: .Selected)
button.setTitle("title 5", forState: .Disabled)

将其放入您的 viewDidLoad() 方法中。

Swift 4:

普通标题

setTitle() 方法适用于在按钮的属性检查器中定义的 "Plain" 的标题。

@IBAction func button(sender: UIButton) { 
     sender.setTitle("buttonName", for: .normal)
}

指定标题

如果在属性检查器中将按钮配置为 "Attributed",则 setTitle() 方法对按钮的标题没有影响。要处理这种情况,首先从按钮获取属性标题,然后设置值。

@IBAction func button(sender: UIButton) { 
     let attributedTitle = sender.attributedTitle(for: .normal)
     attributedTitle?.setValue("buttonName", forKey: "string")
     sender.setAttributedTitle(attributedTitle, for: .normal)
}

这对我有用。

dispatch_async(dispatch_get_main_queue(), ^{
        [self.btnAssment setTitle:@"ASSDate" forState:UIControlStateNormal];
    });

实际上,如果您使用 Storyboard 或 Xib 文件中的按钮,并且不清除 (Storyboard, Xib) 中的按钮值,那么 setTitle 方法将不起作用。如果您清除了按钮值,setTitle 方法将起作用。

let button = UIButton()
button.setTitle("Button", for: .normal)
button.setTitleColor(.black, for: .normal)

我刚刚遇到了类似的问题,这里的 none 答案适用于我的情况。

对我来说,解决方案是在我更改标题后立即调用 button.layoutSubviews() 更新 UIButton 的标签。

(我还必须将按钮类型更改为自定义,否则标题更改会闪烁)