How can I create a button with a background color for tvOS while still showing focus?

前端 未结 8 1004
Happy的楠姐
Happy的楠姐 2021-01-02 05:02

All I want to do is add a background color to a button for all states. But I want to maintain the automatic focus shadow that you get \"for free\" when using a system button

8条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 05:26

    You can use the UIButton method setBackgroundImage(image: UIImage?, forState state: UIControlState) and pass through an image that is a flat color and the state .Normal.

    This image can easily be created programatically from a UIColor and a size of 1x1:

    func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
        let rect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    

提交回复
热议问题