swift how to get UILabel align to top left

本秂侑毒 提交于 2021-01-29 19:03:41

问题


I'm making a trivia app that prints the question out word by word, and currently it starts at the middle of the UILabel and pushes the previous text upward. I'm trying to find out if I can start the first word at the top left of the label, the continue printing the rest.

 func printQuestion ()
    {
        var str = quizbrain.getQuestionText()
        var arr = str.components(separatedBy: " ")
        
        var count = 0

        Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { (t) in
            
            self.questionLabel.text! += " " + arr[count] 
            count += 1
            
            if count == arr.count {
                t.invalidate()
            }
            
            if self.hasBuzzed == true {
                t.invalidate()
            }
            
            
        }



回答1:


I'm trying to find out if I can start the first word at the top left of the label

No, you can’t. That’s not how labels draw when their text changes.

Cool workaround: start with the label containing the whole text, but use an attributed string so that the text is the same color as the background (e.g. white on white) and thus invisible. In your timer, change the color of one word at a time to black.

That way, you never change the text, just the color, so the text does not move as each word is revealed.



来源:https://stackoverflow.com/questions/65056860/swift-how-to-get-uilabel-align-to-top-left

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!