以编程方式快速更改UIButton的文本

时间:2014-10-12 14:42:01

标签: ios xcode swift uibutton

这里的简单问题。我有一个UIButton,currencySelector,我想以编程方式更改文本。这就是我所拥有的:

currencySelector.text = "foobar"

Xcode给出了错误“预期声明”。我做错了什么,如何更改按钮的文字?

11 个答案:

答案 0 :(得分:512)

在Swift 3中:

button.setTitle("Button Title",for: .normal)

否则:

button.setTitle("Button Title", forState: UIControlState.Normal)

答案 1 :(得分:69)

Swift iOS 编程的新用户进行澄清。下面的代码行:

button.setTitle("myTitle", forState: UIControlState.Normal)

仅适用于IBOutlets,而不适用于IBActions

因此,如果您的应用使用按钮作为执行某些代码的功能,比如播放音乐,并且您希望根据切换变量将标题从Play更改为Pause,还需要为该按钮创建IBOutlet

如果您尝试对button.setTitle使用IBAction,则会收到错误消息。它很明显,一旦你知道它,但对于新手(我们都是)这是一个有用的提示。

答案 2 :(得分:9)

斯威夫特4:

$('.text_decoration').click(function () {
    var status;
    $( this ).toggleClass( 'highlight' );
    if($(this).hasClass('highlight'))
    {
        status = true;
    }
    else
    {
        status = false;
    }


    //var text_decoration = $(this).val();
    var text_decoration = $(this).attr('data-action');
    var tObj = canvas.getActiveObject();
    //Check that text is selected
    if(tObj==undefined)
    {
        alert('Please select a Text');
        return false;
    }

    if(text_decoration=='underline')
    {
        tObj.set({
            underline: status
        });
    }
    else if(text_decoration=='linethrough')
    {
        tObj.set({
            linethrough: status
        });
    }
    else if(text_decoration=='overline')
    {
        tObj.set({
            overline: status
        });
    }
    canvas.renderAll();
});

答案 3 :(得分:7)

斯威夫特3:

设置按钮标题:

//for normal state:
my_btn.setTitle("Button Title", for: .normal)

// For highlighted state:
my_btn.setTitle("Button Title2", for: .highlighted)

答案 4 :(得分:5)

Swift 3.0

// Standard State
myButton.setTitle("Title", for: .normal)

答案 5 :(得分:3)

更改标题后的标题有些不同:

我只是遇到一个问题:如果您的UIButton带有标题标题,则必须使用:

my_btn.setAttributedTitle(NSAttributedString(string: my_title), for: my_state)
根据{{​​3}},

为:

  

如果同时为按钮设置标题和属性标题,则该按钮比该按钮更喜欢使用属性标题。

我有一个归属的标题,我试图对其设置setTitle,但没有效果...

答案 6 :(得分:2)

Swift 3

当您进行@IBAction:

@IBAction func btnAction(_ sender: UIButton) {
  sender.setTitle("string goes here", for: .normal)
}

这会将发件人设置为UIButton(而不是Any),因此它将btnAction定位为UIButton

答案 7 :(得分:1)

swift 4.2及更高版本

使用按钮的IBOutlet

btnOutlet.setTitle("New Title", for: .normal)

使用按钮的IBAction

@IBAction func btnAction(_ sender: UIButton) {
  sender.setTitle("New Title", for: .normal)
}

答案 8 :(得分:1)

//正常状态:

btnSecurite.setTitle("TextHear", for: .normal)

答案 9 :(得分:0)

Swift 3

let button: UIButton = UIButton()
button.frame = CGRect.init(x: view.frame.width/2, y: view.frame.height/2, width: 100, height: 100)
button.setTitle(“Title Button”, for: .normal)

答案 10 :(得分:0)

使用swift-04为Xcode中的按钮设置标题: 首先创建一个名为setTitle的方法,其参数标题和UIController状态如下所示;

func setTitle(_ title : String?, for state : UIControl.State)   {

}

并在您的按钮操作方法中调用此方法 喜欢;

yourButtonName.setTitle("String", for: .state)