Here’s what I’m trying to do. If you’ve ever played Halo or CoD, you’d know that you could change the name of a weapon load-out.
What I’m doing is making it so you can change your load-out name using a text field. Here’s the problem, the load-out name in the load-out menu is a button (to select and view info about that load-out) and I could just write this:
@IBAction func renameClassButton(sender: AnyObject) {
classTopButton.text = "(classTopTextField)"
}
Except it [classTopButton] is a button which doesn’t allow the ‘.text’ suffix
asked Oct 29, 2014 at 22:13
You can do:
button.setTitle("my text here", forState: .normal)
Swift 3, 4, and 5:
button.setTitle("my text here", for: .normal)
answered Oct 29, 2014 at 22:25
Steve RosenbergSteve Rosenberg
19.2k7 gold badges45 silver badges52 bronze badges
2
In Xcode 8 — Swift 3:
button.setTitle( "entertext" , for: .normal )
Joshua Dance
7,9904 gold badges62 silver badges64 bronze badges
answered Aug 26, 2016 at 11:49
Nikola LukicNikola Lukic
3,7766 gold badges42 silver badges72 bronze badges
3
It is now this For swift 3,
let button = (sender as AnyObject)
button.setTitle("Your text", for: .normal)
(The constant declaration of the variable is not necessary just make sure you use the sender from the button like this) :
(sender as AnyObject).setTitle("Your text", for: .normal)
Remember this is used inside the IBAction of your button.
answered Dec 5, 2016 at 17:14
Ty VictorsonTy Victorson
2671 gold badge3 silver badges11 bronze badges
NOTE:
line
someButton.setTitle("New Title", forState: .normal)
works only when Title type is Plain.
answered Sep 23, 2019 at 10:14
giacodergiacoder
9608 silver badges21 bronze badges
1
swift 4 work as well as 3
libero.setTitle("---", for: .normal)
where libero is a uibutton
answered Nov 14, 2017 at 23:22
0
You can Use sender argument
@IBAction func TickToeButtonClick(sender: AnyObject) {
sender.setTitle("my text here", forState: .normal)
}
answered Sep 5, 2016 at 20:18
mzonerzmzonerz
1,22015 silver badges22 bronze badges
1
In Swift 4 I tried all of this previously, but runs only:
@IBAction func myButton(sender: AnyObject) {
sender.setTitle("This is example text one", for:[])
sender.setTitle("This is example text two", for: .normal)
}
Jess Bowers
2,7721 gold badge22 silver badges40 bronze badges
answered Jan 26, 2018 at 13:02
Note that if you’re using NSButton there is no setTitle
func, instead, it’s a property.
@IBOutlet weak var classToButton: NSButton!
. . .
classToButton.title = "Some Text"
answered Nov 19, 2016 at 0:32
Nathan F.Nathan F.
3,0602 gold badges31 silver badges67 bronze badges
How do you change the text of the button and disable a button in iOS?
asked Feb 10, 2011 at 7:51
Hey Namratha,
If you’re asking about changing the text and enabled/disabled state of a UIButton, it can be done pretty easily as follows;
[myButton setTitle:@"Normal State Title" forState:UIControlStateNormal]; // To set the title
[myButton setEnabled:NO]; // To toggle enabled / disabled
If you have created the buttons in the Interface Builder and want to access them in code, you can take advantage of the fact that they are passed in as an argument to the IBAction
calls:
- (IBAction) triggerActionWithSender: (id) sender;
This can be bound to the button and you’ll get the button in the sender
argument when the action is triggered. If that’s not enough (because you need to access the buttons somewhere else than in the actions), declare an outlet for the button:
@property(retain) IBOutlet UIButton *someButton;
Then it’s possible to bind the button in IB to the controller, the NIB loading code will set the property value when loading the interface.
zoul
101k43 gold badges256 silver badges350 bronze badges
answered Feb 10, 2011 at 7:59
MGunetilekeMGunetileke
2,1061 gold badge13 silver badges3 bronze badges
2
[myButton setTitle: @"myTitle" forState: UIControlStateNormal];
Use UIControlStateNormal
to set your title.
There are couple of states that UIbuttons provide, you can have a look:
[myButton setTitle: @"myTitle" forState: UIControlStateApplication];
[myButton setTitle: @"myTitle" forState: UIControlStateHighlighted];
[myButton setTitle: @"myTitle" forState: UIControlStateReserved];
[myButton setTitle: @"myTitle" forState: UIControlStateSelected];
[myButton setTitle: @"myTitle" forState: UIControlStateDisabled];
answered Mar 21, 2012 at 18:02
1
If somebody, who is looking for a solution in Swift, landed here, it would be:
myButton.isEnabled = false // disables
myButton.setTitle("myTitle", for: .normal) // sets text
Documentation: isEnabled, setTitle.
Older code:
myButton.enabled = false // disables
myButton.setTitle("myTitle", forState: UIControlState.Normal) // sets text
answered Aug 1, 2014 at 13:16
mikiqexmikiqex
4,8232 gold badges28 silver badges22 bronze badges
1
Assuming that the button is a UIButton
:
UIButton *button = …;
[button setEnabled:NO]; // disables
[button setTitle:@"Foo" forState:UIControlStateNormal]; // sets text
See the documentation for UIButton
.
answered Feb 10, 2011 at 7:59
zoulzoul
101k43 gold badges256 silver badges350 bronze badges
To Change Button title:
[mybtn setTitle:@"My Button" forState:UIControlStateNormal];
[mybtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
For Disable:
[mybtn setEnabled:NO];
answered Jun 25, 2015 at 9:16
Bhavin RamaniBhavin Ramani
3,2215 gold badges31 silver badges41 bronze badges
In Swift 3, you can simply change the title of a button by:
button.setTitle("Title", for: .normal)
and you disable the button by:
button.isEnabled = false
.normal
is the same as UIControlState.normal
because the type is inferred.
answered Oct 29, 2016 at 2:30
lmiguelvargasflmiguelvargasf
59.2k44 gold badges216 silver badges220 bronze badges
1
SWIFT 4 with extension
set:
// set button label for all states
extension UIButton {
public func setAllStatesTitle(_ newTitle: String){
self.setTitle(newTitle, for: .normal)
self.setTitle(newTitle, for: .selected)
self.setTitle(newTitle, for: .disabled)
}
}
and use:
yourBtn.setAllStatesTitle("btn title")
answered Jan 11, 2019 at 14:03
Oz ShabatOz Shabat
1,33615 silver badges16 bronze badges
If you want to change the title as a response to being tapped you can try this inside the IBAction method of the button in your view controller delegate. This toggles a voice chat on and off. Setting up the voice chat is not covered here!
- (IBAction)startChat:(id)sender {
UIButton *chatButton = (UIButton*)sender;
if (!voiceChat.active) {
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Voice Chat"
message:@"Voice Chat will become live. Please be careful with feedback if your friend is nearby."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
[voiceChat start];
voiceChat.active = YES;
[chatButton setTitle:@"Stop Chat" forState:UIControlStateNormal];
}
else {
[voiceChat stop];
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Voice Chat"
message:@"Voice Chat is closed"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
voiceChat.active = NO;
[chatButton setTitle:@"Chat" forState:UIControlStateNormal];
}
}
voiceChat is specific to voice chat of course, but you can use your ow local boolean property to control the switch.
answered Dec 23, 2015 at 15:28
TimTim
1,07812 silver badges25 bronze badges
How do you change the text of the button and disable a button in iOS?
asked Feb 10, 2011 at 7:51
Hey Namratha,
If you’re asking about changing the text and enabled/disabled state of a UIButton, it can be done pretty easily as follows;
[myButton setTitle:@"Normal State Title" forState:UIControlStateNormal]; // To set the title
[myButton setEnabled:NO]; // To toggle enabled / disabled
If you have created the buttons in the Interface Builder and want to access them in code, you can take advantage of the fact that they are passed in as an argument to the IBAction
calls:
- (IBAction) triggerActionWithSender: (id) sender;
This can be bound to the button and you’ll get the button in the sender
argument when the action is triggered. If that’s not enough (because you need to access the buttons somewhere else than in the actions), declare an outlet for the button:
@property(retain) IBOutlet UIButton *someButton;
Then it’s possible to bind the button in IB to the controller, the NIB loading code will set the property value when loading the interface.
zoul
101k43 gold badges256 silver badges350 bronze badges
answered Feb 10, 2011 at 7:59
MGunetilekeMGunetileke
2,1061 gold badge13 silver badges3 bronze badges
2
[myButton setTitle: @"myTitle" forState: UIControlStateNormal];
Use UIControlStateNormal
to set your title.
There are couple of states that UIbuttons provide, you can have a look:
[myButton setTitle: @"myTitle" forState: UIControlStateApplication];
[myButton setTitle: @"myTitle" forState: UIControlStateHighlighted];
[myButton setTitle: @"myTitle" forState: UIControlStateReserved];
[myButton setTitle: @"myTitle" forState: UIControlStateSelected];
[myButton setTitle: @"myTitle" forState: UIControlStateDisabled];
answered Mar 21, 2012 at 18:02
1
If somebody, who is looking for a solution in Swift, landed here, it would be:
myButton.isEnabled = false // disables
myButton.setTitle("myTitle", for: .normal) // sets text
Documentation: isEnabled, setTitle.
Older code:
myButton.enabled = false // disables
myButton.setTitle("myTitle", forState: UIControlState.Normal) // sets text
answered Aug 1, 2014 at 13:16
mikiqexmikiqex
4,8232 gold badges28 silver badges22 bronze badges
1
Assuming that the button is a UIButton
:
UIButton *button = …;
[button setEnabled:NO]; // disables
[button setTitle:@"Foo" forState:UIControlStateNormal]; // sets text
See the documentation for UIButton
.
answered Feb 10, 2011 at 7:59
zoulzoul
101k43 gold badges256 silver badges350 bronze badges
To Change Button title:
[mybtn setTitle:@"My Button" forState:UIControlStateNormal];
[mybtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
For Disable:
[mybtn setEnabled:NO];
answered Jun 25, 2015 at 9:16
Bhavin RamaniBhavin Ramani
3,2215 gold badges31 silver badges41 bronze badges
In Swift 3, you can simply change the title of a button by:
button.setTitle("Title", for: .normal)
and you disable the button by:
button.isEnabled = false
.normal
is the same as UIControlState.normal
because the type is inferred.
answered Oct 29, 2016 at 2:30
lmiguelvargasflmiguelvargasf
59.2k44 gold badges216 silver badges220 bronze badges
1
SWIFT 4 with extension
set:
// set button label for all states
extension UIButton {
public func setAllStatesTitle(_ newTitle: String){
self.setTitle(newTitle, for: .normal)
self.setTitle(newTitle, for: .selected)
self.setTitle(newTitle, for: .disabled)
}
}
and use:
yourBtn.setAllStatesTitle("btn title")
answered Jan 11, 2019 at 14:03
Oz ShabatOz Shabat
1,33615 silver badges16 bronze badges
If you want to change the title as a response to being tapped you can try this inside the IBAction method of the button in your view controller delegate. This toggles a voice chat on and off. Setting up the voice chat is not covered here!
- (IBAction)startChat:(id)sender {
UIButton *chatButton = (UIButton*)sender;
if (!voiceChat.active) {
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Voice Chat"
message:@"Voice Chat will become live. Please be careful with feedback if your friend is nearby."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
[voiceChat start];
voiceChat.active = YES;
[chatButton setTitle:@"Stop Chat" forState:UIControlStateNormal];
}
else {
[voiceChat stop];
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Voice Chat"
message:@"Voice Chat is closed"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
voiceChat.active = NO;
[chatButton setTitle:@"Chat" forState:UIControlStateNormal];
}
}
voiceChat is specific to voice chat of course, but you can use your ow local boolean property to control the switch.
answered Dec 23, 2015 at 15:28
TimTim
1,07812 silver badges25 bronze badges
How to in Swift change UIButton text?
A common mistake, also done by myself some time ago, is to try to change it through an IBAction. You can use an IBAction, but probably not the way you think. A common mistake is to do something like this:
button.text = "Some text"
This will give a compiler error if you try something like that. I would make sense to be able to do it like that. Like in Visual Studio you can change text like that.
I’ll show you two methods on how you can change your UIButton text programmatically.
Swift Change UIButton text – Method 1 (IBOutlet)
In the first method, we will use an IBOutlet to change the button text. First, create a UIButton somewhere on the storyboard. Second, create the IBOutlet the normal way. Call the IBOutlet “button”. And you should end up with something like this:
@IBOutlet weak var button: UIButton!
Now in the viewDidLoad function, we will try to set a new title for the button. Try put in this into the viewDidLoad function:
button.setTitle("Ready", forState: .Normal)
If you try to run your code in the simulator now, your app will start up with the button called Ready. The text from the storyboard should never even appear in your app. I have pasted the complete source code from the example below.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
button.setTitle("Ready", forState: .Normal)
}
}
Swift Change UIButton text – Method 2 (IBAction)
Some might tell you that you can not change the UIButton text without an IBOutlet. In some cases, it might be more practical to use an IBOutlet, if your button should change text without any user interaction. If you want the text to change after the user clicked the button, the IBOutlet is not needed. You can do that from the IBAction directly. Here is how.
In your example create an IBAction for your UIButton. Notice the first word in the parenthesis. It says sender, or at least it should say. That sender represents the UIButton. And you can use the same setTitle function directly with the sender. Check out this example.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func buttonClicked(sender: AnyObject) {
sender.setTitle("Sender", forState: .Normal)
}
}
Try to run that example an see what happens. As soon as you click the button, the text will change to “Sender”.
That is how you in Swift change UIButton text.
Check out UIButton in the swift documentation here https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIButton_Class/
See how to do it on video
Happy texting!
In this short tutorial, you will learn how to set a different font on UIButton in Swift programmatically.
There are lots of different customization you can with UIButton. For example, you might be also interested to learn how to create UIButton and change its style, background color, tint color and make it call a function when tapped.
To set a different font on UIButton programmatically you will need to create a new instance of UIFont object. The initializer of UIFont accepts two arguments: name and size.
UIFont(name: "GillSans-Italic", size: 20)
where the “GillSans-Italic” is a font name you want to set.
Setting Custom UIFont Example
The Swift code example below demonstrates how to create a new button and set a preferred font.
// Create UIButton let myButton = UIButton(type: .system) // Position Button myButton.frame = CGRect(x: 20, y: 20, width: 100, height: 50) // Set text on button myButton.setTitle("Tap me", for: .normal) myButton.titleLabel?.font = UIFont(name: "GillSans-Italic", size: 20)
Here is how this code snippet looks and works when I run it in Xcode Playground.
Bold Title
You can also use a simple system font style to make your button title bold.
UIFont.boldSystemFont(ofSize: 20)
In the code snippet below I will create a new button and will make it use a bold system font style.
// Create UIButton let myButton = UIButton(type: .system) // Position Button myButton.frame = CGRect(x: 20, y: 20, width: 100, height: 50) // Set text on button myButton.setTitle("Tap me", for: .normal) // Make button bold myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
Italic Title
You can also make the button title look italic.
UIFont.italicSystemFont(ofSize: 20)
In the code snippet below I will create a new button and will make it use an italic system font style.
// Create UIButton let myButton = UIButton(type: .system) // Position Button myButton.frame = CGRect(x: 20, y: 20, width: 100, height: 50) // Set text on button myButton.setTitle("Tap me", for: .normal) // Make text italic myButton.titleLabel?.font = UIFont.italicSystemFont(ofSize: 20)
Button Font, Text Color and Background Color
You can use NSMutableAttributedString to combine multiple style properties and apply them to a button title. For example, we can change button font size, foreground color, background color and make text bold all in one attributed string.
let customButtonTitle = NSMutableAttributedString(string: "Tap me", attributes: [ NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.backgroundColor: UIColor.red, NSAttributedString.Key.foregroundColor: UIColor.blue ]) myButton.setAttributedTitle(customButtonTitle, for: .normal)
I hope this short Swift tutorial with code examples was of some value to you. There are many other useful Swift code examples you will find on this blog if you click around.
Happy coding! 🙋🏻♂️
When you develop the iOS app in swift, you can create and set UI component’s attributes both in swift source code and use Xcode attributes inspector. We have learned how to do it programmatically in the article How To Create Multiple Button And Add Button Action Function Programmatically In iOS Swift, this article will tell you how to do it visually with Xcode Attributes Inspector. To make things simple, we choose the swift button as an example.
1. How To Add Swift Button From Xcode Library.
- When you add a swift button programmatically, you need to create an instance of
UIKit.UIButton
class and then set it’s properties ( such as title text, text color, text font, button background color, etc ) in source code also.let btn = UIButton(type: UIButton.ButtonType.system)
- To make the above process visually, you can drag the swift button from Xcode UI Library and then drop it to the Main.storyboard file’s screen view. You can read the article How To Display Xcode Library, Assistant Editor, Inspectors Window to learn more.
2. How To Change Swift Button Attribute In Attributes Inspector.
2.1 Display Xcode Attributes Inspector Pane.
- Before start, select the button component, then click View —> Inspectors —> Show Attributes Inspector menu item at Xcode top menu bar to display the Attributes Inspector pane at Xcode project right side.
- Then you can change the iOS button attributes ( such as title text, text color, text font, button background color, etc ) in the Xcode Attributes Inspector pane.
2.2 Change Button Title Text.
- In the Button area, input button text in the text box under Title attribute. You can see the button text is changed immediately in the screen view.
- You can also input mac os emoji text in the input text box. To do this, press
Control + Command + Space
key at the same time to popup mac os emoji select panel, then select one emoji to input it in the button title text box.
2.3 Change Button Title Text Color.
- In the Button area, select the text color in the Text Color drop-down list. You can select a customized color in the popup color pane.
2.4 Change Button Title Text Font.
- In the Button area, click the
T
icon after Font field, then you can select text font and size.
2.5 Change Button Background Color.
- In the View area, select the button’s background color from the Background drop-down list.
3. How To Change Swift Button Size & Position.
- To change button size and position, you should first open the Xcode Size Inspector pane by click View —> Inspectors —> Show Size Inspector menu item at Xcode top menu bar.
- In this example, we want to make the button width full fill the screen width, make the button height as 30, and make the button center located at the screen center.
3.1 Change Swift Button Size ( Width & Height ).
- Input button Width & Height value in View area, the X & Y value is the button top left point’s location.
- If you want to make the button’s width fully fill the screen width, please click Fill Container Horizontally drop-down item in Arrange —> Position View drop-down list.
- If you want to make the button’s height fully fill the screen height, click Fill Container Vertically in Arrange —> Position View drop-down list.
3.2 Change Swift Button Center Position.
- You can make the button’s center locate at the screen center, to do this, just click Arrange —> Position View —> Center Horizontally In Container drop-down menu item, this will make the button center locate at screen horizontal center. Click the Center Vertically In Container drop-down item to make it’s center position located at screen vertical center.
Introduction
UIButton : UIControl intercepts touch events and sends an action message to a target object when it’s tapped. You can set the title, image, and other appearance properties of a button. In addition, you can specify a different appearance for each button state.
Button Types
A button’s type defines its basic appearance and behavior. After creating a button, you cannot change its type. The most commonly used button types are the Custom and System types, but use the other types when appropriate
-
UIButtonTypeCustom
No button style.
-
UIButtonTypeSystem
A system style button, such as those shown in navigation bars and toolbars.
-
UIButtonTypeDetailDisclosure
A detail disclosure button.
-
UIButtonTypeInfoLight
An information button that has a light background.
-
UIButtonTypeInfoDark
An information button that has a dark background.
-
UIButtonTypeContactAdd
A contact add button.
When creating a custom button—that is a button with the type custom—the frame of the button is set to (0, 0, 0, 0) initially. Before adding the button to your interface, you should update the frame to a more appropriate value.
Creating a UIButton
UIButtons can be initialized in a frame:
Swift
let button = UIButton(frame: CGRect(x: x, y: y, width: width, height: height)
Objective C
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
A specific type of UIButton can be created like this:
Swift
let button = UIButton(type: .Custom)
Objective C
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
where type
is a UIButtonType
:
enum UIButtonType : Int {
case Custom
case System
case DetailDisclosure
case InfoLight
case InfoDark
case ContactAdd
static var RoundedRect: UIButtonType { get }
}
Set title
Swift
button.setTitle(titleString, forState: controlState)
Objective C
[button setTitle:(NSString *) forState:(UIControlState)];
To set the default title to «Hello, World!»
Swift
button.setTitle("Hello, World!", forState: .normal)
Objective C
[button setTitle:@"Hello, World!" forControlState:UIControlStateNormal];
Set title color
//Swift
button.setTitleColor(color, forControlState: controlState)
//Objective-C
[button setTitleColor:(nullable UIColor *) forState:(UIControlState)];
To set the title color to blue
//Swift
button.setTitleColor(.blue, for: .normal)
//Objective-C
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]
Horizontally aligning contents
Swift
//Align contents to the left of the frame
button.contentHorizontalAlignment = .left
//Align contents to the right of the frame
button.contentHorizontalAlignment = .right
//Align contents to the center of the frame
button.contentHorizontalAlignment = .center
//Make contents fill the frame
button.contentHorizontalAlignment = .fill
Objective C
//Align contents to the left
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//Align contents to the right
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//Align contents to the center
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
//Align contents to fill the frame
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
Getting the title label
The underlying title label, if one exists, can be fetched using
Swift
var label: UILabel? = button.titleLabel
Objective C
UILabel *label = button.titleLabel;
This can be used to set the font of the title label, for example
Swift
button.titleLabel?.font = UIFont.boldSystemFontOfSize(12)
Objective C
button.titleLabel.font = [UIFont boldSystemFontOfSize:12];
Disabling a UIButton
A button can be disabled by
Swift
myButton.isEnabled = false
Objective-C:
myButton.enabled = NO;
The button will become gray:
If you don’t want the button appearance to change when disabled set adjustsImageWhenDisabled
to false
/ NO
Adding an action to an UIButton via Code (programmatically)
To add a method to a button, first create an action method:
Objective-C
-(void)someButtonAction:(id)sender {
// sender is the object that was tapped, in this case its the button.
NSLog(@"Button is tapped");
}
Swift
func someButtonAction() {
print("Button is tapped")
}
Now to add this action method to your button, you have to write following line of code:
Objective C
[yourButtonInstance addTarget:self action:@selector(someButtonAction) forControlEvents:UIControlEventTouchUpInside];
Swift
yourButtonInstance.addTarget(self, action: #selector(someButtonAction), forControlEvents: .TouchUpInside)
For ControlEvents parameter, all members of ENUM
UIControlEvents are valid.
Setting Font
Swift
myButton.titleLabel?.font = UIFont(name: "YourFontName", size: 20)
Objective C
myButton.titleLabel.font = [UIFont fontWithName:@"YourFontName" size:20];
Attaching a Method to a Button
To add a method to a button, first create an action method:
Objective-C
-(void) someButtonAction{
NSLog(@"Button is tapped");
}
Swift
func someButtonAction() {
print("Button is tapped")
}
Now to add this action method to your button, you have to write following line of code:
Objective C
[yourButtonInstance addTarget:self action:@selector(someButtonAction) forControlEvents:UIControlEventTouchUpInside];
Swift
yourButtonInstance.addTarget(self, action: #selector(someButtonAction), forControlEvents: .touchUpInside)
For ControlEvents, all members of ENUM
UIControlEvents are valid.
Get UIButton’s size strictly based on its text and font
To get the the exact size of a UIButton’s text based on its font, use the function intrinsicContentSize
.
Swift
button.intrinsicContentSize.width
Objective-C
button.intrinsicContentSize.width;
Set Image
Swift
button.setImage(UIImage(named:"test-image"), forState: .normal)
Objective C
[self.button setImage:[UIImage imageNamed:@"test-image"] forState:UIControlStateNormal];
Multiple Control States
You can also set an image for multiple UIControlStates
, for example to set the same image for the Selected
and Highlighted
state:
Swift
button.setImage(UIImage(named:"test-image"), forState:[.selected, .highlighted])
Objective C
[self.button setImage:[UIImage imageNamed:@"test-image"] forState:UIControlStateSelected|UIControlStateHighlighted];
UIButton (opens new window) : UIControl (opens new window) intercepts touch events and sends an action message to a target object when it’s tapped. You can set the title, image, and other appearance properties of a button. In addition, you can specify a different appearance for each button state.
# Attaching a Method to a Button
To add a method to a button, first create an action method:
Objective-C
Swift
Now to add this action method to your button, you have to write following line of code:
Objective C
Swift
For ControlEvents, all members of ENUM
UIControlEvents (opens new window) are valid.
# Creating a UIButton
UIButtons can be initialized in a frame:
Swift
Objective C
A specific type of UIButton can be created like this:
Swift
Objective C
where type
is a UIButtonType
:
# Set title
Swift
Objective C
To set the default title to «Hello, World!»
Swift
Objective C
# Set title color
To set the title color to blue
# Horizontally aligning contents
Swift
Objective C
# Getting the title label
The underlying title label, if one exists, can be fetched using
Swift
Objective C
This can be used to set the font of the title label, for example
Swift
Objective C
# Disabling a UIButton
A button can be disabled by
Swift
Objective-C:
The button will become gray:
(opens new window)
If you don’t want the button appearance to change when disabled set adjustsImageWhenDisabled
to false
/ NO
# Adding an action to an UIButton via Code (programmatically)
To add a method to a button, first create an action method:
Objective-C
Swift
Now to add this action method to your button, you have to write following line of code:
Objective C
Swift
For ControlEvents parameter, all members of ENUM
UIControlEvents (opens new window) are valid.
# Setting Font
Swift
Objective C
# Get UIButton’s size strictly based on its text and font
To get the the exact size of a UIButton’s text based on its font, use the function intrinsicContentSize
.
Swift
Objective-C
# Set Image
# Swift
# Objective C
# Multiple Control States
You can also set an image for multiple UIControlStates
, for example to set the same image for the Selected
and Highlighted
state:
# Swift
# Objective C
# Button Types
A button’s type defines its basic appearance and behavior. After creating a button, you cannot change its type. The most commonly used button types are the Custom and System types, but use the other types when appropriate
When creating a custom button—that is a button with the type custom—the frame of the button is set to (0, 0, 0, 0) initially. Before adding the button to your interface, you should update the frame to a more appropriate value.