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

前端 未结 8 942
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:30

    Swift 4 /tvOS11 and better:

    Set the ButtonType in the Interface Builder button properties to "Plain".

    Add this private extension to your class:

    private extension UIImage {
    
        static func imageWithColor(color: UIColor, size: CGSize) -> UIImage? {
            let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            UIGraphicsBeginImageContextWithOptions(size, false, 0)
            color.setFill()
            UIRectFill(rect)
            let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return image
        }
    }
    

    Then in your connected IBOutlet set the background image for the focused state of the button:

    @IBOutlet weak var myButton: UIButton! {
        didSet {
            let backgroundImageSelected = UIImage.imageWithColor(color: .red, size: myButton.bounds.size)
            myButton.setBackgroundImage(backgroundImageSelected, for: .focused)
        }
    }
    

提交回复
热议问题