UIView在ViewDidLoad上无法正确移动

时间:2015-03-15 19:56:06

标签: ios swift uiview

@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框移动到正确的位置?

1 个答案:

答案 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
    }
}