|
import UIKit |
|
|
|
class ClearTextButton: UIButton { |
|
|
|
override init(frame: CGRect) { |
|
super.init(frame: frame) |
|
setup() |
|
} |
|
|
|
convenience init() { |
|
self.init(frame: CGRect.zero) |
|
} |
|
|
|
required init?(coder aDecoder: NSCoder) { |
|
fatalError("This view doesn't support NSCoding") |
|
} |
|
|
|
override func setTitleColor(_ color: UIColor?, for state: UIControlState) { |
|
super.setTitleColor(color, for: state) |
|
} |
|
|
|
override func layoutSubviews() { |
|
super.layoutSubviews() |
|
self.refreshMask() |
|
} |
|
|
|
private func setup() { |
|
self.backgroundColor = UIColor.groupTableViewBackground |
|
self.clipsToBounds = true |
|
} |
|
|
|
private func refreshMask() { |
|
self.titleLabel?.backgroundColor = UIColor.clear |
|
self.setTitleColor(UIColor.clear, for: .normal) |
|
|
|
let text: String? = self.titleLabel?.text |
|
let buttonSize: CGSize = self.bounds.size |
|
let font: UIFont? = self.titleLabel?.font |
|
|
|
let textSize: CGSize? = text?.size(withAttributes: [NSAttributedStringKey.font: (self.titleLabel?.font)!]) |
|
|
|
UIGraphicsBeginImageContextWithOptions(buttonSize, false, UIScreen.main.scale) |
|
let ctx: CGContext? = UIGraphicsGetCurrentContext() |
|
ctx?.setFillColor(UIColor.white.cgColor) |
|
|
|
let center = CGPoint(x: buttonSize.width / 2 - (textSize?.width)! / 2, y: buttonSize.height / 2 - (textSize?.height)! / 2) |
|
|
|
let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: buttonSize.width, height: buttonSize.height)) |
|
ctx?.addPath(path.cgPath) |
|
ctx?.fillPath() |
|
ctx!.setBlendMode(.destinationOut) |
|
|
|
text?.draw(at: center, withAttributes: [NSAttributedStringKey.font: font!]) |
|
let viewImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext() |
|
UIGraphicsEndImageContext() |
|
let maskLayer = CALayer() |
|
maskLayer.contents = viewImage?.cgImage as Any |
|
maskLayer.frame = bounds |
|
layer.mask = maskLayer |
|
} |
|
|
|
} |