@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框移动到正确的位置?
答案 0 :(得分:2)
问题是您的子视图是在 viewDidLoad
之后布局的,所以如果您在viewDidLoad
中设置您的IB子视图的位置,那么它将被重新定位到其中的框架视图出现之前的故事板。因此,我建议您将viewDidLoad
中的代码移至viewDidLayoutSubviews
,然后添加dispatch_once块或条件以确保代码仅在第一次调用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
}
}