gpt4 book ai didi

ios - 动态移动(动画)UITextField

转载 作者:行者123 更新时间:2023-11-28 07:01:27 24 4
gpt4 key购买 nike

我一直在尝试为 UITextField 设置动画,使其 y 位置增加 50 像素。基本上,它向上移动了五十个像素。这是我的代码:

@IBAction func textField(sender: AnyObject) {
let x = self.pw.frame.origin.x
let y = self.pw.frame.origin.y + 100
UIView.animateWithDuration(0.5, delay: 0, options: nil, animations: {
self.pw.frame = CGRectMake(x, y, self.pw.frame.size.width, self.pw.frame.size.height)
}, completion: nil)

它在 textField 的委托(delegate)中。当点击 UITextField 时运行此代码。

不幸的是,这段代码并没有按照我的意愿进行。运行时,它会将文本字段向上移动 50 像素,但随后又会向下移动。它并没有在它应该是它的最终位置的地方结束它。

最佳答案

如评论中所述,安装了自动布局约束后,不应手动修改框架。相反,您需要更改约束以反射(reflect)动画的最终结果。

以下是一个最小的工作示例。它创建一个按钮和一个文本字段,并最初将文本字段定位在按钮末尾下方 58 磅的位置。当您点击按钮时,文本字段顶部间距约束的常量从 58 减少到 8 以向上移动文本字段。

class ViewController: UIViewController {

var textFieldTopSpacingConstraint: NSLayoutConstraint?

override func viewDidLoad() {
super.viewDidLoad()

// Create the button
let button = UIButton.buttonWithType(.System) as! UIButton
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.setTitle("Tap me!", forState: .Normal)
button.addTarget(self, action: "buttonTapped", forControlEvents: .TouchUpInside)
view.addSubview(button)

// Create the text field
let textField = UITextField()
textField.placeholder = "Enter text here"
textField.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(textField)

let views: [NSObject: AnyObject] = ["button": button, "textField": textField]

// Layout the button
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[button]-|", options: nil, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[button(44)]", options: nil, metrics: nil, views: views))

// Layout the text field and remember its top spacing constraint
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textField]-|", options: nil, metrics: nil, views: views))
textFieldTopSpacingConstraint = NSLayoutConstraint(item: textField, attribute: .Top, relatedBy: .Equal,
toItem: button, attribute: .Bottom, multiplier: 1, constant: 58) // The text field starts 58 points below the end of the button
view.addConstraint(textFieldTopSpacingConstraint!)
}

func buttonTapped() {
// Change to constant on the top spacing constraint to move the text field up
UIView.animateWithDuration(0.5) {
self.textFieldTopSpacingConstraint?.constant = 8 // The text field now starts 8 points below the end of the button
self.view.layoutIfNeeded()
}
}

}

当您通过 Interface Builder 设置约束后,您可以在 View Controller 中为顶部间距约束创建一个导出,并使用它来修改文本字段的顶部空间。

关于ios - 动态移动(动画)UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com