使用SizeToFit()顶部对齐UILabel会导致跳转

以下代码用于将UILabel中的文本垂直对齐到视图框的左上角。 但是,它会导致文本在适当的垂直顶部对齐和垂直居中之间来回跳动。 跳跃的节奏似乎与位置更新率有关。

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:https://imgflip.com/gif/m82jf

任何想法如何我可以避免这个地狱跳跃?


更新:

如果您正在使用故事板和自动布局,则不应使用sizeToFit()sizeToFit()是“旧”方式的一部分,在自动布局之前,如果Storyboard使用任何Constraints ,则不会像预期那样运行。

而在Interface Builder中:

  • 将行设置为0(允许多行)
  • 根据需要使用任何约束来定位标签
  • 为宽度添加固定约束
  • 使用“小于”或“相等”来为高度添加一个Contraints
  • 这将确保位置正确,并允许自动布局在内容更新时根据需要调整UILabels高度。

    在这里输入图像描述

    更新2:

    不完全确定为什么我拒绝投票,因为建议的答案有效。 在这个例子中,我使用一个计时器来更新我的标签,查看结果:

    在这里输入图像描述

    在这里输入图像描述

    在这里输入图像描述

    在这里输入图像描述

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

    上一篇: Using SizeToFit() to Top Align UILabel Causes Jumping

    下一篇: How to set the UILabel text to be top aligned