Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

ios - UILabel and UITextView line breaks don't match

I have a UILabel and a UITextView, where my intention is for them both to display the same text, and for the appearance to be the same. I'm having some issue with that right now. I've set up a demonstration in a Swift Playground:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.frame = CGRect(x: 100, y: 100, width: 247, height: 39)
        label.numberOfLines = 0
        label.font = UIFont.systemFont(ofSize: 16)
        label.text = "I’m on my way back to London today"
        label.textColor = .black
        label.backgroundColor = .red
        label.lineBreakMode = .byWordWrapping
        view.addSubview(label)

        let textView = UITextView()
        textView.frame = CGRect(x: 100, y: 200, width: 247, height: 39)
        textView.font = label.font
        textView.text = label.text
        textView.textColor = label.textColor
        textView.backgroundColor = label.backgroundColor
        textView.textContainer.lineBreakMode = label.lineBreakMode
        textView.textContainerInset = UIEdgeInsets.zero
        textView.textContainer.lineFragmentPadding = 0
        view.addSubview(textView)

        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

enter image description here

As you can see, they're both setup in the same way, but the linebreak occurs in a different place on the UITextView. I've set the lineBreakMode to the same value for both. I've also removed the textContainerInsets and lineFragmentPadding on the UITextView, so the text is positioned with the same padding within both views.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It was a change to UILabel in IOS 11 to fix orphaned words. No way to shut it off although I wish there was. The only way to do it would be to use a non editable/nonscrollable textview or a CATextLayer. To get the sizing attributes of a UILabel I am afraid you have to do that manually.

See this as the problem was similar. Although not in that answer I did find that UITextView wraps the old way. I am using a UITextView now and I manually adjust the font size in textDidChange. I hold the original font so I can always resize.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...