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 Foundation

2.UIButton Image use

3. Fillet button

4. check box button

5. Countdown button (flicker problem also easy to solve)

6. Greedy button (parent control event also belongs to me, expand incident Response area)

Second, the UIButton Foundation

2.1 Create

UIButton provides a simple way to construct

1 convenience init(type buttonType: UIButtonType)

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

123456789 func createButton() {    let button = UIButton(type: UIButtonType.System)    button.frame = CGRectMake(50, 50, 100, 50)    button.setTitle("确定", 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

1 func setTitleColor(color: UIColor?, forState state: UIControlState)

Cannot be passed

1 button.titleLabel?.text = "确定"

This way the caption automatically changes to the text in the normal state of the Settitlecolor method when clicked.

2.2 Images using

UIButton provides the following two interfaces for using images:

12 func setImage(image: UIImage?, forState state: UIControlState)func setBackgroundImage(image: UIImage?, forState state: 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, and 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 mode

2.2.1.1 principle Description

In the UIImage interface, there are the following methods

1 func resizableImageWithCapInsets(_ capInsets: UIEdgeInsets) -> UIImage

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

1 func UIEdgeInsetsMake(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> UIEdgeInsets

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 uiedgeinsets structure has a pair of attribute top and bottom, which specifies a vertically variable area (a black dashed rectangle), and left and right are a pair 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) The width of the control is greater than the width of the picture, stretched white dashed rectangle

(2) The control height is greater than the height of the picture, stretching the black dashed rectangle

(3) When the width of the control is less than the width of the picture, the overall reduction (variable area and invariant area ratio)

(4) control height is less than the height of the picture, the overall reduction of the longitudinal (variable area and invariant area ratio)

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 the corresponding margin be set according to the X-times graph when used, for example:

123456 let image = 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:

1234 let image = UIImage(named: "tile")let resizeImage = image?.resizableImageWithCapInsets(UIEdgeInsetsZero)self.bkImageView.image = resizeImage2.2.2 Asset Catalogs方式(推荐)

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

123 按钮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:

12 let image = UIImage(named: "image_asset_name")button.setBackgroundImage(image, forState: UIControlState.Normal)

Iii. Other uses of UIButton

3.1 Fillet button

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

123 let image = UIImage(named: "user_avatar")self.button.setImage(image, forState: UIControlState.Normal)self.button.imageView?.layer.cornerRadius = self.button.frame.width / 2

3.2 check box button

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

1234567891011121314151617 func checkBoxButton() {    let frame = CGRectMake(68, 79, 300, 128)    let button = UIButton(type: UIButtonType.Custom)    button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)    button.frame = frame    button.titleLabel?.font = UIFont.systemFontOfSize(30)    button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left    button.setTitle("复选框按钮", forState: UIControlState.Normal)    //上面是样式的设定,下面才是跟复选框有关    button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)    button.setImage(UIImage(named: "check"), forState: UIControlState.Normal)    button.setImage(UIImage(named: "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:

1 let button = 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 you can download directly using: Http://00red.com/download/Swift's greedy uibutton/ilcountdownbutton.swift

Examples of use are:

1234567 let frame = CGRectMake(50, 50, 100, 40)let countButton = ILCountDownButton(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:

12345 class ILGreedButton: UIButton {    override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {        returnself    }}

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

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.