首页 文章

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

提问于
浏览
178

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

currencySelector.text = "foobar"

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

9 回答

  • 6

    斯威夫特3

    当你做@IBAction时:

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

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

  • 0

    只是对 SwiftiOS 编程新手的澄清 . 下面的代码行:

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

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

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

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

  • 1

    斯威夫特3:

    设置按钮 Headers :

    //for normal state:
    my_btn.setTitle("Button Title", for: .normal)
    
    // For highlighted state:
    my_btn.setTitle("Button Title2", for: .highlighted)
    
  • 1

    Swift 3.0

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

    在Swift 3中:

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

    除此以外:

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

    斯威夫特4:

    for state: UIControlState in [.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved] {
            button.setTitle(NSLocalizedString("Title", comment: ""), for: state)
        }
    
  • 5

    在归因时更改 Headers 有点不同:

    我遇到了一个问题:如果你有一个带有归属 Headers 的UIButton,你必须使用:

    my_btn.setAttributedTitle(NSAttributedString(string: my_title), for: my_state)
    

    as,Apple SetTitle Doc

    如果您为按钮设置了 Headers 和属性 Headers ,则该按钮更喜欢使用属于此 Headers 的属性 Headers .

    我有一个属性 Headers ,我试着在它上面设置 Headers ,没有效果......

  • 0

    斯威夫特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)
    
  • 5

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

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

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

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

相关问题