Swift's greedy UIButton

Source: Internet
Author: User

I. SUMMARY OF CONTENTS


Buttons are a very important component in all UI architectures, and the use of button UIButton in iOS is also very flexible, and this article will introduce the use of UIButton ( based on Swift2.0) from the following points:

1.UIButton基础2.UIButton图片使用3.圆角按钮4.复选框按钮5.倒计时按钮(闪烁问题也轻松解决)6.贪婪按钮(父控件事件也归我,扩大事件响应区域)
Ii. UIButton Foundation 2.1 creation

UIButton provides a simple way to construct

buttonType:UIButtonType)

In this method we need to pass in a Uibuttontype enumeration type, using the following code:

Func Createbutton () {Let button =UIButton(Type: Uibuttontype.System) Button.frame =CGRectMake( -, -, -, -) Button.settitle ("OK",forstate: uicontrolstate.Normal) Button.addtarget ( Self,Action: "buttonpressed:",forcontrolevents: uicontrolevents.Touchupinside) Self. View.addsubview (Button)} func buttonpressed (button: UIButton) {    }
Tips:

1. When setting the button title, be sure to pass

    func setTitleColor(color:UIColorstate:UIControlState)

Cannot be passed

    "确定"

This way the title automatically changes to the Settitlecolor method when you click the text in the normal state

2.2 Images using

UIButton provides the following two interfaces for using images:

    func setImage(image:UIImagestate:UIControlState)    func setBackgroundImage(image:UIImagestate:UIControlState

(1) Where the interface setimage is used to set the picture of the button, by default, it will be aligned with the horizontal line of the button text
(2) interface SetBackgroundImage is used to set the background image of the button,setimage and button text will be displayed on the background image
Here is a discussion of the SetBackgroundImage interface, many times, the button looks like this

These buttons, the same background, but not the same size, let's talk about how to reuse this kind of image resources.

2.2.1 Code Method 2.2.1.1 principle Explanation

In the UIImage interface, there are the following methods

func resizableImageWithCapInsets(_capInsets:UIEdgeInsetsUIImage

When using this method, you need to pass uiedgeinsets as a parameter to create the interface as follows:

UIEdgeInsetsMake(_top:CGFloat_left:CGFloat_bottom:CGFloat_right:CGFloatUIEdgeInsets

This method provides the upper and lower parameters to create a variable region , such as (Tips: the variable area indicated and the view padding are different concepts)

In the figure, Blue is identified as a variable area, and the green is identified as an invariant area. The property top of the uiedgeinsets struct is a pair with bottom , which specifies the vertical variable area (black dashed rectangle) , left and right are a pair, Used to specify a transverse variable area (a white dashed rectangle). When the size of Uibutton/uiimageview is larger than UIImage, the variable area in the picture is resized to fill the entire control, with the following rules:

(1)控件宽度大于图片宽度,拉伸白色虚线矩形(2)控件高度大于图片高度,拉伸黑色虚线矩形(3)控制宽度小于图片宽度时,横向整体缩小(可变区与不变区比例不变)(4)控制高度小于图片高度时,纵向整体缩小(可变区与不变区比例不变)

The iOS system automatically loads 1 time times, twice times, and 3 times times according to the device's resolution, while the top and bottom of the method resizableimagewithcapinsets is in pixels, which requires that, when used, according to the x -times graph, To set the corresponding margin, for example:

UIImage(named:"image_name")//1倍图时上下左右边距都是25let padding = 25 * (image?.scale)!let edge = UIEdgeInsetsMake(padding, padding, padding, padding)let resizeImage = image?.resizableImageWithCapInsets(edge)button.setBackgroundImage(resizeImage!, forState: UIControlState.Normal)
The relationship between 2.2.1.2 performance and variable region size

(1) Best performance: When the variable area is 1 pixels wide or high, the drawing is stretched by 1 pixels
(2) Good performance: The variable area is the whole picture, the method resizableimagewithcapinsets parameter is uiedgeinsetszero, when drawing by tiling the whole picture way
(3) Poor performance: When the variable area width or height greater than 1 pixels, the drawing is tiled, this way of poor performance, but in the actual development of this method is also the most used.

Tips

In some applications, the application has some non-solid color background, this background will be used in multiple interfaces, due to the device resolution, interface control size differences, will require the production of multiple dimensions of the diagram, resulting in the IPA package larger, memory usage increased. Here combined with the above (2) to set the variable area for the whole picture, can solve this problem, see the principle of seamless mapping

The sample code is as follows:

UIImage(named:"tile")let resizeImage = image?.resizableImageWithCapInsets(UIEdgeInsetsZero)self.bkImageView.image = resizeImage
2.2.2 Asset catalogs Way (recommended)

Xcode provides the Asset catalogs way to manage the image resources, Asset catalogs provides a visual interface to set the variable area of the picture, easy to operate and easy to use. At the bottom right, click Show slicing

After entering the edit mode, there will be a Start slicing button in the middle of the picture, which will let us choose the stretching method, such as:

Function of three buttons

按钮1只做水平拉伸按钮2水平垂直都拉伸按钮3只做垂直拉伸

Horizontal and vertical stretching process is the same, here in the horizontal, for example, select the horizontal stretching button 1, will provide three lines to specify the variable area and delete area

Variable area: The area specified by the Operation Line 1 and the line 2, which changes the size of the area according to the final dimension when stretched
Delete area: Line 2 and Operation Line 3 specified area (white translucent layer), can be easily understood as, this area will be directly removed when stretching. Using the same method as the normal picture, the code is as follows:

UIImage(named:"image_asset_name"forState:UIControlState.Normal)

Iii. UIButton Other uses 3.1 fillet button

Sometimes, we need a circular button, such as an avatar:

UIImage(named:"user_avatar")selfforState:UIControlState.Normal)selfself2
3.2 check box button

What happens when there are no check box components in Uikit?

Func Checkboxbutton () {Let frame =CGRectMake( the, -, -, -) Let button =UIButton(Type: Uibuttontype.Custom) Button.settitlecolor (Uicolor. Whitecolor (),forstate: uicontrolstate.Normal) Button.frame = Frame Button.titlelabel?. Font =Uifont. Systemfontofsize ( -) Button.contenthorizontalalignment =uicontrolcontenthorizontalalignment. LeftButton.settitle ("check box button",forstate: uicontrolstate.Normal)        //above is the setting of the style, the following is the check box about Button.addtarget (self, Action: "buttonpressed:", forControlEvents:UIControlEvents.TouchUp Inside) Button.setimage (UIImage (named: "Check"), ForState:UIControlState.Normal) button.setimage (UIImage (NA  Med: "uncheck"), forState:UIControlState.Selected) Self.view.addSubview (Button)} Func buttonpressed (button: UIButton) {button.selected =!button.selected}
3.3 Countdown button (flicker problem also easy to solve)

Many applications in the SMS Countdown function, the general will Nstimer and UIButton combination to achieve this function, if UIButton is so early to make:

UIButton(type:UIButtonType.System)

During the test, when the timer changes the title every second, there will be a flicker, change the uibuttontype.system to uibuttontype.custom

Here is a packaged Countdown button that you can download directly using
The greedy uibutton/ilcountdownbutton.swift of Http://00red.com/download/Swift
Examples of use are:

CGRectMake(505010040ILCountDownButton(count:5)countButton.frame = framecountButton.setBackgroundImageForCount(UIImage(named:"bk_count")!)countButton.setBackgroundImageForRestart(UIImage(named:"bk_restart")!)countButton.setTitleForRestart("重新发送")self.view.addSubview(countButton)
Four, greedy button

UIButton frame will directly affect the display of setimage and setbackgroundimage , sometimes we just need to enlarge the UIButton of the click Area, And do not want to directly modify the UIButton frame and affect the display. This can be handled by the following methods

The UIButton's parent view (Superview) 's Click event is occupied and all touch actions are passed on to the UIButton control. iOS is divided into two steps when dealing with event distribution: The first step is to find which UI component responds to this event, the second step, the event handler, and the responder chain. To implement the pass-through of the event, you can do so in the first step, with the following code:

class ILGreedButton: UIButton {    override func hitTest(point:CGPointevent:UIEventUIView? {        returnself    }}

When using Ilgreedbutton , a click on the parent view will appear, UIButton the effect of responding to the event

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Swift's greedy UIButton

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.