如何解决错误的自动换行?

时间:2019-01-27 12:27:27

标签: swift

很长时间以来,我无法解决一个简单的问题,即:将一个单词转移到新行,如果单词不合适则自动缩小标签。告诉我在这种情况下如何做。

@IBOutlet weak var wordLabel: UILabel!
@IBOutlet weak var transcriptionLabel: UILabel!
@IBOutlet weak var translationLabel: UILabel!


var index = 0
var word = ""
var transcription = ""
var translation = ""

override func viewDidLoad() {
    super.viewDidLoad()

    wordLabel.text = word
    transcriptionLabel.text = ""
    translationLabel.text = ""

    wordLabel.adjustsFontSizeToFitWidth = true
    wordLabel.minimumScaleFactor = 0.1

    transcriptionLabel.adjustsFontSizeToFitWidth = true
    transcriptionLabel.minimumScaleFactor = 0.1

    translationLabel.adjustsFontSizeToFitWidth = true
    translationLabel.minimumScaleFactor = 0.1

    self.transcriptionLabel.alpha = 0.0
    self.translationLabel.alpha = 0.0
}

runApp storyboard storyboard

1 个答案:

答案 0 :(得分:0)

感谢humblePilgrim,对于建议的答案,它确实很有帮助。我将链接保留到源中,并附上答案本身。

source

  

Swift 4.2

extension UILabel {
// Adjusts the font size to avoid long word to be wrapped
func fitToAvoidWordWrapping() {
    guard adjustsFontSizeToFitWidth else {
        return // Adjust font only if width fit is needed
    }
    guard let words = text?.components(separatedBy: " ") else {
        return // Get array of words separate by spaces
    }

    // I will need to find the largest word and its width in points
    var largestWord: NSString = ""
    var largestWordWidth: CGFloat = 0

    // Iterate over the words to find the largest one
    for word in words {
        // Get the width of the word given the actual font of the label
        let wordWidth = word.size(withAttributes: [.font: font]).width

        // check if this word is the largest one
        if wordWidth > largestWordWidth {
            largestWordWidth = wordWidth
            largestWord = word as NSString
        }
    }

    // Now that I have the largest word, reduce the label's font size until it fits
    while largestWordWidth > bounds.width && font.pointSize > 1 {
        // Reduce font and update largest word's width
        font = font.withSize(font.pointSize - 1)
        largestWordWidth = largestWord.size(withAttributes: [.font: font]).width
    }
}
} 

我感谢用户Dam的回答。