gpt4 book ai didi

swift - 在 viewDidLoad 中更改 View 位置

转载 作者:搜寻专家 更新时间:2023-10-31 22:29:32 24 4
gpt4 key购买 nike

我正在尝试通过 viewDidLoad 使用此代码在应用程序启动时更改单独的 View 的位置:

let xPosition = dynView.frame.origin.x - 100

//View will slide view
let yPosition = dynView.frame.origin.y;

let height = dynView.frame.size.height
let width = dynView.frame.size.width

UIView.animate(withDuration: 1.0, animations: {

self.dynView.frame = CGRect(x: xPosition, y: yPosition, width: width, height: height)


})

但是,这似乎不能直接在 viewDidLoad 中工作如果我使用 @IBAction

分配给按钮,代码就可以工作

我猜我在这里遗漏了什么,但我不知道是什么。

最佳答案

引用您在评论中关于使用约束的回答:

Yes, I do. I'm assuming this has something to do with it? Is the constraints loaded after the viewDidLoad?

没错,来自viewDidLoad()文档:

Called after the controller's view is loaded into memory.

与检查约束设置是否已完成( subview 已布局)无关。

如果我没记错的话,你要找的是 viewDidLayoutSubviews()方法:

Called to notify the view controller that its view has just laid out its subviews.

Your view controller can override this method to make changes after the view lays out its subviews. The default implementation of this method does nothing.

因此,与其在 viewDidLoad() 中实现更改 View 的 y 位置的代码,不如尝试让它在 viewDidLayoutSubviews() 中实现,如下所示:

override func viewDidLoad() {
super.viewDidLoad()
}

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()

let xPosition = dynView.frame.origin.x - 100
let yPosition = dynView.frame.origin.y

let height = dynView.frame.size.height
let width = dynView.frame.size.width

UIView.animate(withDuration: 1.0, animations: {
self.dynView.frame = CGRect(x: xPosition, y: yPosition, width: width, height: height)
})
}

还有:如果你不想让动画在弹出/关闭下一个 ViewController 后重复播放,你可以声明一个 flag 属性来确定是否开始动画,类似于:

var isAnimated = false

override func viewDidLayoutSubviews() {
if isAnimated == false {
super.viewDidLayoutSubviews()

UIView.animate(withDuration: 1.0, animations: {
self.btn.frame.origin.y = 20
}, completion: { _ in
self.isAnimated = true
})
}
}

补充说明:

我建议更改约束值而不是直接更改帧大小/原点。您可能想查看 this question/answer.

关于swift - 在 viewDidLoad 中更改 View 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41329927/

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