I create a button programmatically..........
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(aMethod:)
fo
Solution in Swift 3:
button.setTitleColor(UIColor.red, for: .normal)
This will set the title color of button.
With Swift 5, UIButton
has a setTitleColor(_:for:) method. setTitleColor(_:for:)
has the following declaration:
Sets the color of the title to use for the specified state.
func setTitleColor(_ color: UIColor?, for state: UIControlState)
The following Playground sample code show how to create a UIbutton
in a UIViewController
and change it's title color using setTitleColor(_:for:)
:
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
// Create button
let button = UIButton(type: UIButton.ButtonType.system)
// Set button's attributes
button.setTitle("Print 0", for: UIControl.State.normal)
button.setTitleColor(UIColor.orange, for: UIControl.State.normal)
// Set button's frame
button.frame.origin = CGPoint(x: 100, y: 100)
button.sizeToFit()
// Add action to button
button.addTarget(self, action: #selector(printZero(_:)), for: UIControl.Event.touchUpInside)
// Add button to subView
view.addSubview(button)
}
@objc func printZero(_ sender: UIButton) {
print("0")
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller
You can use -[UIButton setTitleColor:forState:]
to do this.
Example:
Objective-C
[buttonName setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
Swift 2
buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)
Swift 3
buttonName.setTitleColor(UIColor.white, for: .normal)
Thanks to richardchildan
If you are using Swift, this will do the same:
buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)
Hope that helps!
You created the UIButton
is added the ViewController
, The following instance method to change UIFont
, tintColor
and TextColor
of the UIButton
Objective-C
buttonName.titleLabel.font = [UIFont fontWithName:@"LuzSans-Book" size:15];
buttonName.tintColor = [UIColor purpleColor];
[buttonName setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
Swift
buttonName.titleLabel.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purpleColor()
buttonName.setTitleColor(UIColor.purpleColor(), forState: .Normal)
Swift3
buttonName.titleLabel?.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purple
buttonName.setTitleColor(UIColor.purple, for: .normal)