IOS

IOS TutorialAirPrint tutorial in iOSCarthage iOS SetupChecking iOS versionCore SpotLight in iOSCreate a Custom framework in iOSDeep Linking in iOSExtension for rich Push Notification - iOS 10.Guideline to choose best iOS Architecture PatternsIOS - Implementation of XMPP with Robbie Hanson frameworkIOS 3D TouchIOS 10 Speech Recognition APIIOS AccessibilityIOS ADDING a SWIFT BRIDGING HEADERIOS AFNetworkingIOS AirDropIOS AlamofireIOS App Submission ProcessIOS App Transport Security (ATS)IOS App wide operationsIOS AppDelegateIOS Application rating/review requestIOS ARC (Automatic Reference Counting)IOS attributedText in UILabelIOS Auto LayoutIOS AVPlayer and AVPlayerViewControllerIOS AVSpeechSynthesizerIOS AWS SDKIOS Background ModesIOS Background Modes and EventsIOS Basic text file I/OIOS BlockIOS CAAnimationIOS Cache online imagesIOS CAGradientLayerIOS CALayerIOS CAShapeLayerIOS CategoriesIOS CGContext ReferenceIOS Chain Blocks in a Queue (with MKBlockQueue)IOS Change Status Bar ColorIOS Checking for Network ConnectivityIOS CLLocationIOS CloudKitIOS CodableIOS Code signingIOS ConcurrencyIOS Configure Beacons with CoreBluetoothIOS Contacts FrameworkIOS Content Hugging/Content Compression in AutoLayoutIOS Convert HTML to NSAttributed string and vice verseIOS Convert NSAttributedString to UIImageIOS Core DataIOS Core GraphicsIOS Core LocationIOS Core MotionIOS CoreImage FiltersIOS Create .ipa File to upload on appstore with ApplicationloaderIOS Create a video from imagesIOS Creating an App IDIOS CTCallCenterIOS Custom fontsIOS Custom KeyboardIOS Custom methods of selection of UITableViewCellsIOS Custom UITextFieldIOS Custom UIViews from XIB filesIOS Cut a UIImage into a circleIOS CydiaSubstrate tweakIOS Debugging CrashesIOS DispatchGroupIOS Dynamic TypeIOS Dynamically updating a UIStackViewIOS EventKitIOS Face Detection Using CoreImage/OpenCVIOS FacebookSDKIOS FastlaneIOS FCM Messaging in SwiftIOS FileHandleIOS GameCenter LeaderboardsIOS GameplayKitIOS GCD (Grand Central Dispatch)IOS Google Places APIIOS Graph (Coreplot)IOS Handle Multiple Environment using MacroIOS Handling URL SchemesIOS HealthkitIOS iBeaconIOS IBOutletsIOS In-App PurchaseIOS Initialization idioms



IOS UIButton

From WikiOD

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.

Remarks[edit | edit source]

Button Types[edit | edit source]

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.

Attaching a Method to a Button[edit | edit source]

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.

Creating a UIButton[edit | edit source]

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[edit | edit source]

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];

Horizontally aligning contents[edit | edit source]

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[edit | edit source]

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[edit | edit source]

A button can be disabled by

Swift

myButton.isEnabled = false

Objective-C:

myButton.enabled = NO;

The button will become gray:

UIButton

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)[edit | edit source]

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[edit | edit source]

Swift

myButton.titleLabel?.font =  UIFont(name: "YourFontName", size: 20)

Objective C

myButton.titleLabel.font = [UIFont fontWithName:@"YourFontName" size:20];

Set title color[edit | edit source]

//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]

Get UIButton's size strictly based on its text and font[edit | edit source]

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[edit | edit source]

Swift[edit | edit source]

button.setImage(UIImage(named:"test*image"), forState: .normal)

Objective C[edit | edit source]

[self.button setImage:[UIImage imageNamed:@"test-image"] forState:UIControlStateNormal];

Multiple Control States[edit | edit source]

You can also set an image for multiple UIControlStates, for example to set the same image for the Selected and Highlighted state:

Swift[edit | edit source]

button.setImage(UIImage(named:"test*image"), forState:[.selected, .highlighted])

Objective C[edit | edit source]

[self.button setImage:[UIImage imageNamed:@"test-image"] forState:UIControlStateSelected|UIControlStateHighlighted];

Credit:Stack_Overflow_Documentation