Changing UIButton text

后端 未结 7 1382
遇见更好的自我
遇见更好的自我 2020-12-25 10:23

So I\'m trying to update the text on a UIButton when I click it. I\'m using the following line to change the text:

calibrationButton.titleLabel.text = @\"Cal         


        
相关标签:
7条回答
  • 2020-12-25 11:02

    If you don't want to set the title for all states, just set it for the normal state since the title for the unset states will default to the title of the normal state.

    btn.setTitle("Some text", for:.normal)
    
    0 讨论(0)
  • 2020-12-25 11:08

    For Swift 3.0

    let button = UIButton(type: .system)
    button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
    button.setTitle("set here", for: .normal)
    button.addTarget(self, action: #selector(TableViewController.actionButtonTocuh), for: .touchUpInside)
    button.titleLabel?.textColor  = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1)
    view.addSubview(button)
    
    0 讨论(0)
  • 2020-12-25 11:10

    To set button text use the following method:

    [calibrationButton setTitle: @"Calibration" forState: UIControlStateNormal];
    

    See UIButton class reference for more details... http://developer.apple.com/library/ios/#documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html

    Or in Swift 3:

    calibrationButton.setTitle("Calibration", for: .normal)
    
    0 讨论(0)
  • 2020-12-25 11:11

    For Swift 2.0:

    let btnObject : UIButton  = UIButton() 
    btnObject.frame = CGRect(x: 8, y: 89, width: 70, height: 22)
    btnObject.setTitle("Button Title", forState: UIControlState.Normal)
    btnObject.titleLabel?.font = UIFont(name: "Helvetica Neue", size: 13)
    btnObject.titleLabel?.textColor = UIColor.whiteColor()
    btnObject.backgroundColor = UIColor(red: 189/255, green: 176/255, blue: 0/255, alpha: 1)
    btnObject.titleLabel?.textAlignment = NSTextAlignment.Center
    btnObject.addTarget(self, action: "btnbtnObjectClick:", forControlEvents: UIControlEvents.TouchUpInside)
    subView.addSubview(btnObject)
    
    0 讨论(0)
  • 2020-12-25 11:13

    When laying out its subviews, a UIButton will set its titleLabel's text value using its own title values, so that you can set up to four different strings for the four states (normal, highlighted, selected, disabled).

    Because of this feature, setting the titleLabel's text directly won't persist, and will be reset by the button when it lays out its subviews.

    This is what you have to do to change the title text for a button's state.

    [calibrationButton setTitle:@"Calibration" forState:UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-25 11:14

    programmatically you can set button title like below:

    [myButton setTitle:@"buttonTitle" forState:UIControlStateNormal];
    

    you can also set button title property from storyboard.

    0 讨论(0)
提交回复
热议问题