sterling archer
sterling archer

Reputation: 334

XCode/Swift cannot change text label position

Im trying to randomly change the position of a label on my screen and its not working. however, this same code works if i open a new xcode project. also, note the print statement at the bottom of my code. it does in fact print a different location every time the function is called, but does not change the position of the label.

func displayCurrGoal() {

    self.label.text = "heyyy"

    // Find the labels width and height
    let labelWidth = self.label.frame.width
    let labelHeight = self.label.frame.height

    // Find the width and height of the enclosing view
    let labelViewWidth = self.label.superview!.bounds.width
    let labelViewHeight = self.label.superview!.bounds.height

    // Compute width and height of the area to contain the labels center
    let labelXwidth = labelViewWidth - viewWidth
    let labelYheight = labelViewHeight - viewHeight

    // Generate a random x and y offset
    let viewXoffset = CGFloat(arc4random_uniform(UInt32(labelXwidth)))
    let viewYoffsset = CGFloat(arc4random_uniform(UInt32(labelYheight)))

    // Offset the labels center by the random offsets.
    self.label.center.x = viewXoffset + labelWidth / 2
    self.label.center.y = viewYoffset + labelHeight / 2


    //test if coordinate is changing every time func is called 
    println(self.label.center.y) }

also, autoformatting is not enabled.

Upvotes: 1

Views: 4501

Answers (2)

user817238593
user817238593

Reputation: 131

This is correct approach so u must be using cocoapods or something. if so, the imageview u are using is probably fixed, so u need to try something different...

Upvotes: 1

Sash Zats
Sash Zats

Reputation: 5466

  • Do you see the label presented on the screen?
  • Do you see the text being changed to "heyyy"?
  • What does label.constraints() return?
  • Try setting position to hardcoded numbers

Normally view.center.x = 100 works

Upvotes: 0

Related Questions