Skip to content

Instantly share code, notes, and snippets.

@nakiwo
Created October 6, 2017 14:10
Show Gist options
  • Save nakiwo/7957aaa1b03f84cafe27c100840e6c99 to your computer and use it in GitHub Desktop.
Save nakiwo/7957aaa1b03f84cafe27c100840e6c99 to your computer and use it in GitHub Desktop.
関連づけられたラベルの色をステートに合わせて変えるUIButton。ハイライト時のフェードアニメーション付き
import UIKit
class MyButton: UIButton {
@IBOutlet weak var associatedLabel: UILabel? {
didSet {
associatedLabel?.textColor = currentTitleColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override var isHighlighted: Bool {
didSet {
UIView.animate(withDuration: 0.2) {
let alpha: CGFloat = self.isHighlighted ? 0.3 : 1
self.alpha = alpha
self.associatedLabel?.alpha = alpha
}
associatedLabel?.textColor = currentTitleColor
}
}
override var isEnabled: Bool {
didSet {
associatedLabel?.textColor = currentTitleColor
}
}
override var isSelected: Bool {
didSet {
associatedLabel?.textColor = currentTitleColor
}
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let label = associatedLabel else {
return super.point(inside: point, with: event)
}
let labelBounds = convert(label.bounds, from: label)
let unionBounds = bounds.union(labelBounds)
return unionBounds.contains(point)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment