@IBOutlet var box: UIView!
var lastLocation:CGPoint = CGPointMake(200,400) //arbitrary value that will change
override func viewDidLoad() {
super.viewDidLoad()
box.center = lastLocation
lastLocation = box.center
}
@IBAction func detectPan(sender: UIPanGestureRecognizer) {
var translation = sender.translationInView(self.view!)
box.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y)
println(box.center)
if(sender.state == UIGestureRecognizerState.Ended)
{
lastLocation = box.center
}
}
每当代码接收到平移手势时,盒子就会适当移动,但在 viewDidLoad() 上盒子不会重新定位到给定位置。在 IB 中它被设置在左上角并且最后的位置会改变,所以我不能简单地移动 IB 中的框。我该怎么做才能将 viewDidLoad 框移动到正确的位置?
最佳答案
问题是你的 subview 是在 viewDidLoad
之后布局的,所以如果你在 viewDidLoad
中设置你的 IB subview 的位置,它就会在 View 出现之前将其重新定位到 Storyboard 中的框架。所以我建议将 viewDidLoad
中的代码移动到 viewDidLayoutSubviews
然后添加一个 dispatch_once block 或条件以确保代码只在第一次运行 viewDidLayoutSubviews
被调用,例如:
override func viewDidLayoutSubviews() {
func doOnce() {
struct Token {
static var token: dispatch_once_t = 0;
}
dispatch_once(&Token.token) {
self.box.center = lastLocation
self.lastLocation = box.center
}
}
doOnce()
}
或
var subviewsLaidout = false
override func viewDidLayoutSubviews() {
if subviewsLaidout == false {
subviewsLaidout = true
box.center = lastLocation
lastLocation = box.center
}
}
关于ios - UIView 不会在 ViewDidLoad 上正确移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29065456/