出来ること
- StoryBoardでも確認できる
- Focusのイベントをコントロールできる
- ボタンのTitleが中央揃えにする
RoundButton.swift
import UIKit
@IBDesignable
class RoundButton: UIButton{
override init(frame: CGRect) {
super.init(frame: frame)
self.initView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initView()
}
func initView(){
self.titleLabel?.textAlignment = .center
}
@IBInspectable var cornerRadius: CGFloat = 0{
didSet{
self.layer.cornerRadius = cornerRadius
}
}
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({
if self.isFocused {
// in focus
UIView.animate(withDuration: 0.1,
animations: {
self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
self.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).cgColor
self.layer.shadowOffset = CGSize(width: 5, height: 5)
self.layer.shadowOpacity = 1.0
self.layer.shadowRadius = 5.0
},
completion:nil)
}
else {
// leaving focus
UIView.animate(withDuration: 0.1,
animations: {
self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowOpacity = 0.0
self.layer.shadowRadius = 0.0
},
completion:nil)
}
}, completion: nil)
}
}
使い方
- StoryBoardでUIButtonのCustomClassをRoundButtonにする
- StoryBoardでCorner Radiusの値を調整する
留意
StoryBoardに反映できない場合がある。その際、以下を確認ください。
- RoundButtonクラスを追加した時点、一旦、Xcodeを再起動したら、問題なく反映できると思う。
- XcodeのEditor/Automatically Refresh Viewsをオンにするかを確認する