简体   繁体   中英

How to force display update in Swift

I'm making a Tic Tac Toe application where I want to center the board when the view has been loaded.

I've made a centerBoard() function that gets called in viewDidLoad() . This is the code of the function:

func centerBoard() {
    print("centerBoard() triggered")
    let centerX = (outerView.frame.size.width)/2
    boardView.center = CGPointMake(centerX,250)
    if boardView.center == CGPoint(x: centerX,y: 250) {
        print("centerBoard() successful")
    }
    boardView.setNeedsLayout()
    boardView.setNeedsDisplay()
}

However, the board doesn't change place when the view is loaded, only when the test button is pressed, despite running the exact same code. I made the if statement to check if the board's center has been updated, and it prints successful everytime, both when the view has loaded and when the button is pressed.

Print out to the console the center coordinates in viewDidLayoutSubviews. Probably your settings are overridden by autolayout, viewDidLayoutSubviews is called a couple of times after viewDidLoad was called. Set the center for your view through the autolayout system, or turn off the autolayout for the xib/storyboard if you don't want to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM