2016-12-26 74 views
-1

我試圖定義在我的文本中出現軟換行符的位置,並且NSLayoutManagerDelegate方法layoutManager(_:shouldBreakLineByWordBeforeCharacterAt:)看起來像是開始的地方。我的問題是它沒有被調用,儘管我的其他方法是。這發生在基本的UITextView設置。在這種方法稱爲什麼條件下 - 我在正確的地方尋找?如何確定TextKit發生軟線斷裂的位置?

這裏是我的TextKit堆棧的樣子:

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 
    } 

} 
+0

@matt更新。雖然堆棧不一定是完全自定義的 - 我剛剛設置了一個委託/ – mattsven

+0

@matt我在Playground中嘗試使用實時視圖。也許就是這樣? – mattsven

+1

我洗了整個事情的手。遊樂場是魔鬼的工作。 – matt

回答

1

我在實際的應用程序想你的代碼,並佔據整個上海華文本視圖,並shouldBreakLineByWordBeforeCharacterAt在推出多次調用如果初始字符串很長,然後每次用戶輸入一個字符時都會如此 - 完全如預期。

+0

就是這樣,遊樂場正在使用一個真正的應用程序來解決問題。既然你看起來是知識淵博的,我真正想做的是絕對的位置角色。我最初的想法是使用'shouldBreakLineByWordBeforeCharacterAt'來決定哪裏出現換行符,用'NSTextContainer.lineFragmentRect(forProposedRect:)'來決定'行'的位置。這是一個好方法嗎? – mattsven

+0

「我真正想做的是絕對位置角色」這將是一個單獨的(和有趣的)問題。 – matt