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
180 views
in Technique[技术] by (71.8m points)

ios - How to decide where soft line-breaks occur with TextKit?

I'm trying to define where soft line breaks occur within my text, and the NSLayoutManagerDelegate method layoutManager(_:shouldBreakLineByWordBeforeCharacterAt:) seems like the place to start. My problem is it's not getting called, although my other methods are. This is occurring with a basic UITextView setup. Under what conditions is this method called - am I looking in the right place?

Here's what my TextKit stack looks like:

class DemoTextView: UITextView, NSLayoutManagerDelegate {

    //  MARK: - Init

    required init() {
        let textStorage = NSTextStorage(string: "i will overflow several lines probably just saying")

        let layoutManager = NSLayoutManager()

        textStorage.addLayoutManager(layoutManager)

        let textContainer = NSTextContainer(size: CGSize(width: 100, height: 100))

        textContainer.lineBreakMode = .byWordWrapping
        textContainer.lineFragmentPadding = 0

        layoutManager.addTextContainer(textContainer)

        //  Super

        super.init(frame: .zero, textContainer: textContainer)

        self.textContainerInset = .zero

        //  Configure Text View

        layoutManager.delegate = self

        self.isScrollEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    //  Layout Manager

    func layoutManager(_ layoutManager: NSLayoutManager, shouldBreakLineByWordBeforeCharacterAt charIndex: Int) -> Bool {
        print(#function)

        return false
    }

    func layoutManager(_ layoutManager: NSLayoutManager, shouldBreakLineByHyphenatingBeforeCharacterAt charIndex: Int) -> Bool {
        print(#function)

        return false
    }

}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I tried your code in an actual app, with the text view occupying the entire superview, and shouldBreakLineByWordBeforeCharacterAt is called multiple times at launch if the initial string is long, and then again every time the user types a character — exactly as expected.


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

...