topLayoutGuide.length 折旧

topLayoutGuide.length depreciated

我仍然是 xCode 的初学者,如果有人能帮助我,我会很高兴。这是我的代码:

if(magnetLinkTextField.frame.origin.y<=0) {
            UIView.animate(withDuration: 0.2, animations: {
                self.magnetLinkTextField.frame = CGRect(x: self.magnetLinkTextField.frame.origin.x,
                                                        y: self.topLayoutGuide.length,
                                                        width: self.magnetLinkTextField.frame.size.width,
                                                        height: self.magnetLinkTextField.frame.size.height)
            }
        }

如何实现以下内容:

'topLayoutGuide' was deprecated in iOS 11.0: Use view.safeAreaLayoutGuide.topAnchor instead of topLayoutGuide.bottomAnchor

我使用自动布局和动画复制并粘贴到一个新项目中以查看它,以编程方式为您创建了这个示例: 首先在 ViewController class

下声明您的文本字段和按钮(以激活动画)
let yourTextfield = UITextField()
let button = UIButton()

之后声明用于动画的约束变量:

var goToTop: NSLayoutConstraint?
var stayHere: NSLayoutConstraint?

现在在 viewDidLoad 中构造文本字段和按钮,为按钮分配一个动作,呈现它们并添加约束:

view.backgroundColor = .red
    
    button.backgroundColor = .blue
    button.setTitle("put on top", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.addTarget(self, action: #selector(handleGo), for: .touchUpInside)
    button.translatesAutoresizingMaskIntoConstraints = false
    
    yourTextfield.attributedPlaceholder = NSAttributedString(string: "Your textfield", attributes: [.foregroundColor: UIColor(white: 0, alpha: 0.3)])
    yourTextfield.textColor = .black
    yourTextfield.backgroundColor = UIColor(white: 1, alpha: 0.5)
    yourTextfield.translatesAutoresizingMaskIntoConstraints = false
    
    view.addSubview(yourTextfield)
    yourTextfield.widthAnchor.constraint(equalToConstant: 300).isActive = true
    yourTextfield.heightAnchor.constraint(equalToConstant: 50).isActive = true
    yourTextfield.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    stayHere = yourTextfield.centerYAnchor.constraint(equalTo: view.centerYAnchor)
    stayHere?.isActive = true
    goToTop = yourTextfield.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
    
    view.addSubview(button)
    button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    button.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20).isActive = true
    button.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20).isActive = true
    button.heightAnchor.constraint(equalToConstant: 50).isActive = true

现在编写动画函数:

@objc fileprivate func handleGo() {
    UIView.animate(withDuration: 0.5, animations: {
        self.stayHere?.isActive = false
        self.goToTop?.isActive = true
        self.view.layoutIfNeeded()
    }, completion: nil)
}

这是结果,请根据您的项目进行调整...希望对您有所帮助:)