Using SizeToFit() to Top Align UILabel Causes Jumping

The following code works to vertically align text in a UILabel to the top-left of the view box. However, it causes the text to jump back and forth between proper vertical top alignment and vertical centering. The cadence of it's jumping seems to be about that of the location update rate.

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    var userlocation: CLLocation = locations[0] as! CLLocation

    CLGeocoder().reverseGeocodeLocation(userlocation, completionHandler: {
        (placemarks, error) -> Void in

        if( error != nil )
        {
            println("Error: (error.localizedDescription)")
            return
        }

        if( placemarks.count > 0 )
        {
            let placeMark = placemarks[0] as! CLPlacemark
            self.nearestAddressLabel.text = ABCreateStringWithAddressDictionary(placeMark.addressDictionary, false);

            self.nearestAddressLabel.sizeToFit()
        }
        else
        {
            println("No placemarks!")
        }

    })
}

GIF of problem: https://imgflip.com/gif/m82jf

Any idea how I can avoid this infernal jumping around?


UPDATE:

If you are using storyboard and auto layout you should not use the sizeToFit() . sizeToFit() is part of the "old" way, pre Auto Layout, and will not behave as expected if Storyboard uses any Constraints .

Instead in Interface Builder:

  • Set Lines to 0 (Allow many lines)
  • Position the label as needed using any Constraints
  • Add a fixed Constraint for width
  • Add a Contraints for height using Less Than or Equal
  • This will make sure the position is correct, and allow for the Auto Layout to resize the UILabels height as needed when content is updated.

    在这里输入图像描述

    UPDATE 2:

    Not entirely sure why I got down voted, as the suggested answer works. In this example, I am using a timer to update my label, see result:

    在这里输入图像描述

    在这里输入图像描述

    在这里输入图像描述

    在这里输入图像描述

    链接地址: http://www.djcxy.com/p/28266.html

    上一篇: 如何在段落中对齐UILabel文本

    下一篇: 使用SizeToFit()顶部对齐UILabel会导致跳转