简体   繁体   中英

Swift: How to make a label in the borders of the screen?

I'm trying to create a game that generates labels randomly on the screen, but the entire word must be inside the screen. I also have a textfield in the screen that I'm intending to put the words beneath.

I have a function for adding a label, and another for making sure It's inside the borders.

func addWord(word: String) {
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let screenWidth = UInt32(screenSize.width)
    let screenHeight = UInt32(screenSize.height)
    let label = UILabel()
    label.text = word
    label.font = UIFont.systemFontOfSize(32)
    label.sizeToFit()
    label.backgroundColor = UIColor.whiteColor()

    let x = CGFloat(arc4random_uniform(screenWidth))
    let y = CGFloat(arc4random_uniform(screenHeight))

    label.center = CGPointMake(x, y)
    label.center = checkBounds(label, minX: 0, maxX: CGFloat(screenWidth), minY: (newWordsTextField.bounds.origin.y+newWordsTextField.bounds.maxY), maxY: CGFloat(screenHeight))
    view.addSubview(label)

    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.handlePanGesture(_:)))
    label.addGestureRecognizer(panGesture)
    label.userInteractionEnabled = true
}

func checkBounds(label: UILabel, minX: CGFloat, maxX: CGFloat, minY: CGFloat, maxY: CGFloat)->CGPoint{
    let borders = label.bounds
    var newCenter = label.center
    if borders.minX < minX {
        newCenter.x = newCenter.x + (minX-borders.minX)
    }
    if borders.maxX > maxX {
        newCenter.x = newCenter.x-(borders.maxX-maxX)
    }
    if borders.minY < minY {
        newCenter.y = newCenter.y + (minY-borders.minY)
    }
    if borders.maxY > maxY {
        newCenter.y = newCenter.y-(borders.maxY-maxY)
    }
    return newCenter
}

but for some reason the labels keep getting out of the boundaries even though the function should've made sure that wouldn't happen. I'm kind of new to swift and it's the first time I'm trying something like this, help please, what am I doing wrong?

If you're using Auto Layout (you almost certainly are because it's the default and you have to turn it off manually) then the frame and center of your view objects gets overridden by Auto Layout constraints (either once you define or ones the system creates automatically.)

If you're going to add views manually then you need to add constraints as well. That should fix your problem. I suggest googling "add UIViews and constraints through code" or something similar to find tutorials on how it's done (or better yet just add the views in your storyboard and mark them as hidden until you need them.

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