Swift realizes the free adjustment icon and text position in the icon button (extended UIButton)

Source: Internet
Author: User
Tags reserved touch uikit

Button UIButton is one of the most common controls in iOS development, and the details of UIButton are described below, as well as the issues that need to be noticed in development.


UIButton Introduction:

Use the target action design pattern, target-action mode, one of 3 types of callback patterns.

Implementation principle:

Use the following method to package, depending on the user's click to move and so on


-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event;
-(void) touchesmoved: (Nsset *) touches withevent: (Uievent *) event;
-(void) touchesended: (Nsset *) touches withevent: (Uievent *) event;
-(void) touchescancelled: (Nsset *) touches withevent: (Uievent *) event; Create button:


Constructor method that calls the method to create a button object for a style
+ (ID) Buttonwithtype: (Uibuttontype) ButtonType

Parameters:
ButtonType: Button style
Enumeration values:
Uibuttontypecustom = 0, custom style uibuttontyperoundedrect, rounded rectangle
Uibuttontypedetaildisclosure, Blue small arrow button, mainly to do detailed instructions with
Uibuttontypeinfolight, Bright exclamation
Uibuttontypeinfodark, Dark exclamation
Uibuttontypecontactadd, Cross plus button Uibuttontypesystem, system default style, if you use this style, you will see an exception when using SetImage

Example:
UIButton *button = [UIButton buttonwithtype:uibuttontyperoundedrect];
Configure button caption
//Get Caption text for button, read-only property
@ Property (Nonatomic, ReadOnly, retain) Uilabel *titlelabel, note do not use Titlelabel directly to modify title
//return in a state, the button's caption text
-( NSString *) Titleforstate: (uicontrolstate) State

Parameters:
State: Control Status
Enumeration values:
UIControlStateNormal//Normal state appears
uicontrolstatehighlighted//Highlight status Show
uicontrolstatedisabled//Disabled status will only appear
uicontrolstateselected//checked status Uicontrolstateapplication//When application flags
uicontrolstatereserved//reserved for the internal frame, can be whatever he
Return value: The caption text for the button in this state

Example:
NSString *title = [button Titleforstate:uicontrolstatenormal];
Set the caption text for a button in a state
-(void) Settitle: (NSString *) title
Forstate: (uicontrolstate) state

Example:
[Button settitle:@ "forstate:uicontrolstatenormal];
Returns the rich text of a button caption in a state
-(Nsattributedstring *) Attributedtitleforstate: (uicontrolstate) state

Parameters:
State: Status of the control
Return value: Rich Text
Nsattirbutedstring for rich Text, see nsattirbutedstring documentation for details


Example:
nsattributedstring *attributedstring = [button Attributedtitleforstate:uicontrolstatenormal];
Set the rich text caption of a value button in a state
-(void) Setattributedtitle: (nsattributedstring *) title
Forstate: (uicontrolstate) state
Returns the caption color of a button in a state
-(Uicolor *) Titlecolorforstate: (uicontrolstate) state

Parameters:
State: Status
return value: Color

Example:
Uicolor *color = [button Titlecolorforstate:uicontrolstatenormal];
Set the color of a button caption
-(void) Settitlecolor: (Uicolor *) color
Forstate: (uicontrolstate) state

Parameters:
Color: Coloring Description Object
State: Status

Example:
[Button Settitlecolor:[uicolor Redcolor] forstate:uicontrolstatenormal];
Returns the shadow color of a button caption in a state
-(Uicolor *) Titleshadowcolorforstate: (uicontrolstate) state
Sets the shadow color of a button caption in a state
-(void) Settitleshadowcolor: (Uicolor *) color
Forstate: (uicontrolstate) state

Parameters:
Color: Coloring Description Object
State: Status

Example:
[Button Settitleshadowcolor:[uicolor Graycolor] forstate:uicontrolstatenormal];
Whether the button is highlighted when the shadow of the caption changes. Default is No
@property (nonatomic) BOOL reversestitleshadowwhenhighlighted
Configuration button Demo
If the button is highlighted, the color of the image needs to be deepened. The default is Yes
@property (nonatomic) BOOL adjustsimagewhenhighlighted
If the button is disabled, the color of the image should be darker. The default is Yes
@property (nonatomic) BOOL adjustsimagewhendisabled
Whether the button will glow if pressed. Default is No
@property (nonatomic) BOOL showstouchwhenhighlighted
Returns the background picture of a button in a state
-(UIImage *) Backgroundimageforstate: (uicontrolstate) state

Parameters:
State: Status
Return value: Background image

Example:
UIImage *image = [button Backgroundimageforstate:uicontrolstatenormal];
Get a fill picture of a button
-(UIImage *) Imageforstate: (uicontrolstate) state
Set the background picture of a button
-(void) SetBackgroundImage: (UIImage *) image
Forstate: (uicontrolstate) state

Parameters:
Image: Background picture
State: Status

Example:
[Button Setbackgroundimage:image Forstate:uicontrolstatenormal];
Set the fill picture for a button
-(void) SetImage: (UIImage *) image
Forstate: (uicontrolstate) state
Configure button Border effects
Sets the distance of the button's inner content (including the button picture and caption) up or down from the edge of the button.
@property (nonatomic) uiedgeinsets contentedgeinsets

Structure Body:
CGFloat top, left, bottom, right;
Four values, the upper left, the lower right, respectively.
Sets the internal caption of a button from the top or bottom edge of the button
@property (nonatomic) uiedgeinsets titleedgeinsets
Sets the internal picture of the button from the top or bottom edge of the button
@property (nonatomic) uiedgeinsets imageedgeinsets
Gets the current state of the button (read-only)
Get button state, read-only property
@property (nonatomic, readonly) Uibuttontype ButtonType
Gets the current caption of the button, read-only property
@property (Nonatomic, ReadOnly, retain) NSString *currenttitle
Gets the current rich text caption of the button
@property (Nonatomic, ReadOnly, retain) nsattributedstring *currentattributedtitle
Get the color of the current title
@property (Nonatomic, ReadOnly, retain) Uicolor *currenttitlecolor
Gets the shadow color of the current caption
@property (Nonatomic, ReadOnly, retain) Uicolor *currenttitleshadowcolor
Get a picture of the current button
@property (Nonatomic, ReadOnly, retain) UIImage *currentimage
Get the background picture of the current button
@property (Nonatomic, ReadOnly, retain) UIImage *currentbackgroundimage
Gets the picture frame object for the current button
@property (Nonatomic, ReadOnly, retain) Uiimageview *imageview
overriding drawing behavior
You can customize the button class that belongs to you by using the subclass button. In subclasses you can overload the following methods, which return the CGRect structure, indicating the bounds of each component of the button.

Note: Do not call these methods directly, which you write to the system call.

Specify background boundary
-(CGRect) Backgroundrectforbounds: (CGRect) bounds
Specify content Boundaries
-(CGRect) Contentrectforbounds: (CGRect) bounds
Specify text title boundaries
-(CGRect) Titlerectforcontentrect: (CGRect) Contentrect
Specify Button Image boundaries
-(CGRect) Imagerectforcontentrect: (CGRect) Contentrect

Example:
-(CGRect) Imagerectforcontentrect: (CGRect) bounds{
Return CGRectMake (0.0, 0.0, 44, 44);
}
Event
Add a Click event to a button
[Button addtarget:self action: @selector (Action:) forcontrolevents:uicontroleventtouchupinside];

Enumeration values:
Uicontroleventtouchdown//Single point Touch press event: The user touches the screen, or when a new finger falls.
Uicontroleventtouchdownrepeat//Multi-Touch press event, point touch count is greater than 1: when the user presses the second to third or fourth finger.
Uicontroleventtouchdraginside//When a touch is dragged inside the control window.
Uicontroleventtouchdragoutside//When a touch is dragged outside the control window.
Uicontroleventtouchdragenter//When a touch is dragged from outside the control window to the interior
Uicontroleventtouchdragexit//When a touch is dragged from inside the control window to the outside.
UIControlEventTouchUpInside//All touch lift events within the control
Uicontroleventtouchupoutside//All controls outside the control to lift the event (the touch must start with the inside of the control to send a notification).
Uicontroleventtouchcancel//All touch cancellation events, that is, a touch was canceled because it was put on too many fingers, or was locked or interrupted by a phone call.

Uicontroleventvaluechanged//When the value of the control changes, the notification is sent. Used for sliders, segmented controls, and other value-taking controls. You can configure when a slider control sends a notification, sends it when the slider is dropped, or sends it when it is dragged.

Uicontroleventeditingdidbegin//Send notification when editing is started in a text control
uicontroleventeditingchanged//notification is sent when text in a text control is changed.
Uicontroleventeditingdidend//Send notification at the end of editing in a text control.
Uicontroleventeditingdidendonexit///When the text control ends editing by pressing the ENTER key (or equivalent behavior), the notification is sent.

Uicontroleventalltouchevents//Notify all touch events.
Uicontroleventalleditingevents//Notifies all events about text editing.
Uicontroleventapplicationreserved//Range available for application use
uicontroleventsystemreserved//range reserved for internal framework use
Uicontroleventallevents//Notify All Events

Implementation of check box checkbox:

First to select, why not select the time to set the background picture

When you click the button, take the selected value

Using the selected state, you can reverse the selection

Sample code:


-(void) Checkboxclick: (UIButton *) btn
{
btn.selected =!btn.selected;
}

-(void) Viewdidload {
UIButton *checkbox = [UIButton buttonwithtype:uibuttontypecustom];

CGRect checkboxrect = CGRectMake (135,150,36,36);
[CheckBox Setframe:checkboxrect];

[CheckBox setimage:[uiimage imagenamed:@ "Checkbox_off.png"] forstate:uicontrolstatenormal];
[CheckBox setimage:[uiimage imagenamed:@ "Checkbox_on.png"] forstate:uicontrolstateselected];

[CheckBox addtarget:self Action: @selector (Checkboxclick:) forcontrolevents:uicontroleventtouchupinside];
[Self.view Addsubview:checkbox];
}

Free adjust icon and text position in icon button (extended UIButton)


1,custom type of UIButton
We can set the icon in front of the text using the custom type button. But the relative position of the picture and the text is fixed (the button is in front, the text is behind).
(1) We make a button with an icon with the left image (64*64) below

Create a button that adds text to a picture
Let Btn1:uibutton = UIButton (Frame:cgrect (x:50, y:50, width:180, height:32))
Btn1.setimage (UIImage (named: "Alert"), ForState:UIControlState.Normal)//button icon
Btn1.titlelabel? Font = uifont.boldsystemfontofsize (28)//Text size
Btn1.settitle ("With icon button", forState:UIControlState.Normal)//Button text
Btn1.settitlecolor (Uicolor.orangecolor (), forState:UIControlState.Normal)//Text color
Self.view.addSubview (BTN1)

(2) The spacing between pictures and text 1-set picture offset (imageedgeinsets)


1


Btn1.imageedgeinsets = Uiedgeinsets (top:0, left: -20, bottom:0, right:0)

(3) The spacing between pictures and text 2-set text offset (titleedgeinsets)

Btn1.titleedgeinsets= uiedgeinsets (top:0, left:20, bottom:0, right:0)

2, extended UIButton

If we want to change the text and the position of the picture (that is, the text before, the picture in the back), or text and pictures to move up and down, then the same by setting Titleedgeinsets and imageedgeinsets can be achieved.
To quickly set the relative position of the picture and the text, as well as the spacing, the UIButton is extended here.

(1) The extension code is as follows:
Import Uikit

Extension UIButton {

@objc func Set (Image Animage:uiimage?, title:string,
Titleposition:uiviewcontentmode, Additionalspacing:cgfloat, state:uicontrolstate) {
Self.imageview? Contentmode =. Center
Self.setimage (Animage, Forstate:state)

Positionlabelrespecttoimage (title, Position:titleposition, spacing:additionalspacing)

Self.titlelabel? Contentmode =. Center
Self.settitle (title, forstate:state)
}

Private Func Positionlabelrespecttoimage (title:string, Position:uiviewcontentmode,
Spacing:cgfloat) {
Let ImageSize = Self.imagerectforcontentrect (self.frame)
Let Titlefont = Self.titlelabel? font!
Let titlesize = Title.sizewithattributes ([nsfontattributename:titlefont!])

var titleinsets:uiedgeinsets
var imageinsets:uiedgeinsets

Switch (position) {
Case. Top:
Titleinsets = Uiedgeinsets (top:-(imagesize.height + titlesize.height + spacing),
Left:-(ImageSize.Width), bottom:0, right:0)
Imageinsets = Uiedgeinsets (top:0, left:0, bottom:0, right:-titlesize.width)
Case. Bottom:
Titleinsets = Uiedgeinsets (top: (imagesize.height + titlesize.height + spacing),
Left:-(ImageSize.Width), bottom:0, right:0)
Imageinsets = Uiedgeinsets (top:0, left:0, bottom:0, right:-titlesize.width)
Case. Left:
Titleinsets = Uiedgeinsets (top:0, left:-(ImageSize.Width * 2), bottom:0, right:0)
Imageinsets = Uiedgeinsets (top:0, left:0, bottom:0,
Right:-(Titlesize.width * 2 + spacing))
Case. Right:
Titleinsets = Uiedgeinsets (top:0, left:0, bottom:0, right:-spacing)
Imageinsets = Uiedgeinsets (top:0, left:0, bottom:0, right:0)
Default
Titleinsets = Uiedgeinsets (top:0, left:0, bottom:0, right:0)
Imageinsets = Uiedgeinsets (top:0, left:0, bottom:0, right:0)
}

Self.titleedgeinsets = Titleinsets
Self.imageedgeinsets = Imageinsets
}
}

(2) using the sample

Import Uikit

Class Viewcontroller:uiviewcontroller {

Override Func Viewdidload () {
Super.viewdidload ()

Let Btn1:uibutton = UIButton (Frame:cgrect (x:0, y:0, width:200, height:32))
Btn1.center = Cgpointmake (VIEW.FRAME.SIZE.WIDTH/2, 60)
Btn1.titlelabel? Font = uifont.boldsystemfontofsize (28)//Text size
Btn1.settitlecolor (Uicolor.orangecolor (), forState:UIControlState.Normal)//Text color
Btn1.set (Image:uiimage (named: "Alert"), Title: "Text on the left", Titleposition:. Left,
additionalspacing:10.0, state:. Normal)
View.addsubview (BTN1)


Let Btn2:uibutton = UIButton (Frame:cgrect (x:0, y:0, width:200, height:32))
Btn2.center = Cgpointmake (VIEW.FRAME.SIZE.WIDTH/2, 120)
Btn2.titlelabel? Font = uifont.boldsystemfontofsize (28)//Text size
Btn2.settitlecolor (Uicolor.orangecolor (), forState:UIControlState.Normal)//Text color
Btn2.set (Image:uiimage (named: "Alert"), Title: "Text on the right", titleposition:. Right,
additionalspacing:10.0, state:. Normal)
View.addsubview (BTN2)

Let Btn3:uibutton = UIButton (Frame:cgrect (x:0, y:0, width:170, height:70))
Btn3.center = Cgpointmake (VIEW.FRAME.SIZE.WIDTH/2, 230)
Btn3.titlelabel? Font = uifont.boldsystemfontofsize (28)//Text size
Btn3.settitlecolor (Uicolor.orangecolor (), forState:UIControlState.Normal)//Text color
Btn3.set (named: "Alert"), Title: "Text Above", Titleposition:. Top,
additionalspacing:10.0, state:. Normal)
View.addsubview (BTN3)

Let Btn4:uibutton = UIButton (Frame:cgrect (x:0, y:0, width:170, height:70))
Btn4.center = Cgpointmake (VIEW.FRAME.SIZE.WIDTH/2, 290)
Btn4.titlelabel? Font = uifont.boldsystemfontofsize (28)//Text size
Btn4.settitlecolor (Uicolor.orangecolor (), forState:UIControlState.Normal)//Text color
Btn4.set (named: "Alert"), Title: "Text at the bottom", titleposition:. Bottom,
additionalspacing:10.0, state:. Normal)
View.addsubview (BTN4)
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.