UIButton
サブクラスを作成しようとしており、選択状態と無効状態の背景画像を色で表示しようとしています。 UIButtonは、私は(ボタンをタップしたとき、私は状態を変更します)ボタンを選択すると、奇妙なと思うが、ボタンは初回のみを検出することでそれが動作しない丸いエッジself.layer.cornerRadius = self.frame.height/2
UIButtonさまざまな状態の色の背景画像
class RoundedButton: UIButton {
public var shadowOffset: CGSize = CGSize(width:0, height:0) {
didSet{
self.layer.shadowOffset = shadowOffset
}
}
public var shadowRadius: CGFloat = 0.0 {
didSet{
self.layer.shadowRadius = shadowRadius
}
}
public var shadowOpacity: Float = 1.0 {
didSet{
self.layer.shadowOpacity = shadowOpacity
}
}
public var shadowColor: UIColor = UIColor.black {
didSet{
self.layer.shadowColor = shadowColor.cgColor
}
}
public var selectedBackgroundColor: UIColor = UIColor.black
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.frame.height/2
self.setBackgroundImage(getImageWithColor(color: selectedBackgroundColor, size: self.frame.size, cornerRadius: self.frame.height/2), for: .selected)
}
func getImageWithColor(color: UIColor, size: CGSize, cornerRadius: CGFloat?) -> UIImage? {
let rect = CGRect(x:0, y:0, width:size.width, height:size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
if cornerRadius != nil {
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius!).addClip()
}
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
となりますされていますタップ別の奇妙な振る舞いは、普通のUIImage
(コアグラフィックスでは作成されていません)を割り当てた場合、生成される画像に問題がある可能性があります。
私は、シャドー、コーナーの半径と、UIColorと異なる背景ボタンの状態の色を持つことができることに注意してください。