viewDidLoad보다 먼저 실행되는 loadView()에 작성하기로 함.
import UIKit
class ViewController: UIViewController {
var myViewBottomConstraint : NSLayoutConstraint?
//bottom앵커가 변하게 되므로 var로 선언.
override func loadView() {
super.loadView()
self.view.backgroundColor = .systemOrange //view의 배경색
let upButton = UIButton(type: .system) //눌렀을 때 느낌
let myView = UIView()
self.view.addSubview(upButton)
upButton.translatesAutoresizingMaskIntoConstraints = false
upButton.setTitle("위로 올리기", for: .normal)
upButton.setTitleColor(.black, for: .normal)
upButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 30)
upButton.backgroundColor = .white
upButton.layer.cornerRadius = 8
upButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
upButton.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 200).isActive = true
upButton.addTarget(self, action: #selector(moveViewUp), for: .touchUpInside) //액션을 넣어줌.
upButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
self.view.addSubview(myView)
myView.translatesAutoresizingMaskIntoConstraints = false
myView.backgroundColor = .blue
myView.layer.cornerRadius = 8
NSLayoutConstraint.activate([
myView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
myView.widthAnchor.constraint(equalToConstant: 100),
myView.heightAnchor.constraint(equalToConstant: 50),
//myView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
])
myViewBottomConstraint = NSLayoutConstraint(item: myView, attribute: .bottom, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0)
// constant를 변경시켜주기위해 이렇게 설정.
myViewBottomConstraint?.isActive = true
}
@objc fileprivate func moveViewUp(){
print("ViewController - viewDidLoad()")
UIViewPropertyAnimator(duration: 1, curve: .easeIn, animations: {
self.view.layoutIfNeeded()
}).startAnimation()
myViewBottomConstraint?.constant -= 100
}
// 버튼을 누를때마다 위로 올라가도록 100씩 마이너스해줌.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
@objc에서 애니메이션을 넣었는데 잘 안됐다. 나중에 다시 해봐야겠다.