我有一个圆形的likeButton,它位于圆形的moreButton后面。 likeButton固定在moreButton的centerX和centerY上。当我按下moreButton时,我希望对moreButton上方200点的likeButton进行动画处理。
我使用NSLayoutConstraint
来跟踪likeButton的centerY并对其进行更改。当我调用UIView.animate
并在其闭包内部调用self.view.layoutIfNeeded()
时,视图未更新。
@objc func moreButtonTapped(){
likeButtonCenterY?.isActive = false
likeButton.centerYAnchor.constraint(equalTo: self.moreButton.centerYAnchor, constant: -200)
likeButtonCenterY?.isActive = true
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
我要去哪里了?
let moreButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "more"), for: .normal)
button.tintColor = .red
button.clipsToBounds = true
button.addTarget(self, action: #selector(moreButtonTapped), for: .touchUpInside)
return button
}()
let likeButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "like"), for: .normal)
button.tintColor = .blue
button.clipsToBounds = true
return button
}()
var likeButtonCenterY: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setAnchors()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
moreButton.layer.cornerRadius = moreButton.frame.size.width / 2
likeButton.layer.cornerRadius = likeButton.frame.size.width / 2
}
@objc func moreButtonTapped(){
likeButtonCenterY?.isActive = false
likeButton.centerYAnchor.constraint(equalTo: self.moreButton.centerYAnchor, constant: -200)
likeButtonCenterY?.isActive = true
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
func setAnchors(){
view.addSubview(likeButton)
view.addSubview(moreButton)
moreButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
moreButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -200).isActive = true
moreButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
moreButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
likeButtonCenterY = likeButton.centerYAnchor.constraint(equalTo: moreButton.centerYAnchor)
likeButtonCenterY?.isActive = true
likeButton.centerXAnchor.constraint(equalTo: moreButton.centerXAnchor).isActive = true
likeButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
likeButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
最佳答案
试试这个
@objc func moreButtonTapped(){
likeButtonCenterY?.isActive = false
likeButtonCenterY = likeButton.centerYAnchor.constraint(equalTo: self.moreButton.centerYAnchor, constant: -200)
likeButtonCenterY?.isActive = true
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
您忘记写
likeButtonCenterY =