简体   繁体   中英

How to create UIButton with custom shape in Swift?

I need to create button like this 在此处输入图片说明

and the change the background programmatically like this 在此处输入图片说明

and like this 在此处输入图片说明

I can not use images for different states of a button because each time I have different text on it.

What to start from ? I tried to understand CoreGraphics and CoreAnimation but there is too small amount of examples and tutorials so my attempts didn't give me any success.

You can , and should, use an image for this. UIKit has a method resizableImageWithCapInsets that creates resizable images. You feed it a minimum sized image and the system stretches it to fit the desired size. It looks like your image is fixed in height, which is good since you can't do smooth gradients with this technique.

UIButton s are composed of a background image and title text, so you can use an image for the background shapes ( setBackgroundImage(_:forState:) ), and then change the text using setTitle(_:forState:) .

However, you can still use Core Graphics for this, and there are benefits to doing so, such as the fact that it reduces the number of rendered assets in your app bundle. For this, probably the best approach is to create a CAShapeLayer with a path constructed from a UIBezierPath , and then render it into a graphics context. From this context, you can pull out a UIImage instance, and treat it just the same as an image loaded from a JPEG or PNG asset (that is, set it as the buttons background image using setBackgroundImage(_:forState:) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM