はじめに
UIControlを勉強することがありましたので、復習を兼ねて
こんな感じのAnimationするButtonを作ってみます
Animation Button pic.twitter.com/fbZQvRXVjV
— Moto (@Moto_0124) May 18, 2019
実装
ViewController
Buttonを設置してConstraintsを設置していきます。
今回はleading,trailing,topに意味はなく,Heightだけ設置したいAnimationButtonの高さにして、ButtonHeight,ButtonをそれぞれViewControllerに接続します
Button
同じようにConstraintsを設置していきます。
こちらもConstraintsは設置しなくても構わないのですが、Buttonに載せる部品だけは指定してあげます。
出ないとButtonと一緒に移動せず、そのままalphaが減少するだけになってしまいます
ButtonのOutletは押したのをButtonで受け取って、ViewControllerを操作するためViewではなく、FileOwnerに接続します
SourceCode
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button: AnimationButton!{
didSet{
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .primaryActionTriggered)
button.backgroundColor = .gray
}
}
@IBOutlet weak var buttonHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func buttonTapped(_ sender: AnimationButton) {
UIView.animate(withDuration: 3.0, animations: {
self.updateConstraint()
})
}
private func updateConstraint(){
buttonHeightConstraint.constant = button.hiddenSwitch.isSelected ? button.bounds.height + 100 : 50
view.layoutIfNeeded()
}
}
import UIKit
class AnimationButton: UIControl {
@IBOutlet weak var hiddenSwitch: UIButton!{
didSet{
hiddenSwitch.setTitle("View Hidden Switch", for: .normal)
hiddenSwitch.titleLabel?.font = UIFont.systemFont(ofSize: 18.0)
hiddenSwitch.titleLabel?.adjustsFontSizeToFitWidth = true
}
}
@IBOutlet weak var descritpionLabel: UILabel!
public override init(frame: CGRect) {
super.init(frame: frame)
xibInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibInit()
}
private func xibInit(){
guard let view = UINib(nibName: String(describing: type(of: self)), bundle: nil).instantiate(withOwner: self, options: nil).first as? UIView else{
return
}
self.addSubview(view)
self.translatesAutoresizingMaskIntoConstraints = false
let constraints:[NSLayoutConstraint] = [
self.topAnchor.constraint(equalTo: view.topAnchor),
self.bottomAnchor.constraint(equalTo: view.bottomAnchor),
self.leadingAnchor.constraint(equalTo: view.leadingAnchor),
self.trailingAnchor.constraint(equalTo: view.trailingAnchor)
]
NSLayoutConstraint.activate(constraints)
descritpionLabel.alpha = 0.0
}
@IBAction func buttonTouchUpInside(_ sender: UIButton) {
hiddenSwitch.isSelected = !hiddenSwitch.isSelected
hiddenSwitch.layoutIfNeeded()
UIView.animate(withDuration: 3.0, animations: {
if self.hiddenSwitch.isSelected{
self.descritpionLabel.alpha = 1.0
}else{
self.descritpionLabel.alpha = 0.0
}
})
sendActions(for: .primaryActionTriggered)
}
}
sendActions
を使って、ViewControllerで指定した.primaryActionTriggered
のActionを呼び出します
そうすることにより、ButtonをViewControllerから操作できます
まとめ
アプリやGitHubをみているとかっこいいUIComponentをよくみるので、自分でも少しずつこういった自作Componentを勉強して作っていきたいと思います