如何确定TextKit在何处出现软换行符? [英] How to decide where soft line-breaks occur with TextKit?

查看:186
本文介绍了如何确定TextKit在何处出现软换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图定义在文本中出现换行符的位置,并且NSLayoutManagerDelegate方法layoutManager(_:shouldBreakLineByWordBeforeCharacterAt:)似乎是开始的地方.我的问题是,尽管我的其他方法却没有得到调用.这是通过基本的UITextView设置发生的.这种方法在什么情况下称为-我在正确的位置看吗?

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?

这是我的TextKit堆栈的样子:

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
    }

}

推荐答案

我在实际应用中尝试了您的代码,其中文本视图占据了整个超级视图,如果初始字符串为shouldBreakLineByWordBeforeCharacterAt,则在启动时会多次调用shouldBreakLineByWordBeforeCharacterAt很长,然后每次用户键入一个字符时都会再次输入-完全符合预期.

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.

这篇关于如何确定TextKit在何处出现软换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆