UILabel在添加文本时反弹

时间:2014-10-30 19:43:38

标签: ios swift ios8 autolayout nslayoutconstraint

文本以编程方式添加到UILabel。随着更多文本的添加,文本会包装并增加标签的高度。

问题是,当文本包裹在一行的末尾时,整个标签将跳过1行的高度并将其自身动画回到其正确的位置。最终结果很好,但是你怎么摆脱奇怪的跳跃动画。同样,每当UILabel的高度由于另一个换行而增加时,就会发生这种情况。

示例代码:

var eventCount = 0;
func someEvent(sender:AnyObject){
    eventCount += 1;
    if(eventCount == 1){
        lbl.text = "this"
    }else if(eventCount == 2){
        lbl.text = "this is some" 
    }else if(eventCount == 3){
        lbl.text = "this is some sample text" 
    }else if(eventCount == 4){
        // this is where text wraps to line 2 
        // the label jumps up 20px or so and 
        //  animates back down to it's original position 
        lbl.text = "this is some sample text that causes the label to wrap" 
    }
}

自动布局约束

            0
            |
     0 - UILabel - 0

标签属性

lines = 0

1 个答案:

答案 0 :(得分:3)

我设法使用以下代码重现问题:

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    @IBAction func buttonPushed(sender: AnyObject) {
        UIView.animateWithDuration(0.5) {
            self.someEvent(self)
            self.view.layoutIfNeeded()
        }
    }

    func someEvent(sender:AnyObject){
        self.label.text! += " test"
    }
}

所以,我相信你的someEvent()是在动画块中调用的。

UIView.performWithoutAnimation解决了这个问题。

var eventCount = 0;
func someEvent(sender:AnyObject){
    UIView.performWithoutAnimation {
        self.eventCount += 1;
        if(self.eventCount == 1){
            self.lbl.text = "this"
        }else if(self.eventCount == 2){
            self.lbl.text = "this is some"
        }else if(self.eventCount == 3){
            self.lbl.text = "this is some sample text"
        }else if(self.eventCount == 4){
            self.lbl.text = "this is some sample text that causes the label to wrap"
        }
        self.view.layoutIfNeeded()
    }
}