In Swift, I wonder if there is a way to get whether or not a word is wrapped. For example, I have an UILabel.
let label = UILabel()
label.text = "Hey! Hello World!"
label.areWordsWrapped()
If text is displaying like this:
Hey! Hell
o World!
//label.areWordsWrapped() should return true
if this:
Hey! Hello
World!
//label.areWordsWrapped() should return false
Is there a function or property to achieve that?
You can try this, it may not perfect
extension UILabel {
func areWordsWrapped()->Bool {
let fontAttributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font: self.font!]
let splitText: [String] = self.text!.split {$0 == " "}.map(String.init)
for text in splitText {
let width = text.size(withAttributes: fontAttributes).width
if width > self.frame.width {
return true
}
}
return false
}
}
edit:
it will be fail if you change the line break to character wrap
if use default line break it will be fine
if you use character wrap I think it almost certain it will be wrapped, because it almost impossible to have same width in every line without enter/new line