ios - UIView 不会在 ViewDidLoad 上正确移动

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

最佳答案

问题是你的 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/

相关文章:

swift - 使用 CGAffineTransform MakeRotation 时无法增加 UIView 的高度和宽度

ios - 什么时候继承 UITableView?

ios - 如何将导航栏按钮放置在自定义位置

ios - Swift:添加到新 View 时,图像不会出现在 ImageView 中

ios - 将类从 Storyboard附加到 TableView 时出现问题

ios - drawRect 和 Interface Builder 之间的颜色差异?

ios - 调用 Auth.auth().signOut() 会自动关闭 ViewController

ios - 如何使 UITableView 的节标题完全透明

ios - 将项目从 Objective C 移动到 Swift 时,类型 'AnyHashable' 的值没有下标

swift - 保存条形图 View 时不显示条形图