Counting the number of lines in a UITextView, lines wrapped by frame size

前端 未结 13 1471
逝去的感伤
逝去的感伤 2020-11-27 03:42

I wanted to know when a text is wrapped by the frame of the text view is there any delimiter with which we can identify whether the text is wrapped or not.

For insta

13条回答
  •  余生分开走
    2020-11-27 04:07

    Improved and update Luke Chase's answer to Swift 5, XCode 11, iOS 13 to get text view number of lines and autoresize table view cell height.

    1. You can use storyboard with static cell height to design it as you want. Make UITextView scroll enable: false (disable scroll).

    2. In viewDidLoad add your estimated row height and your textView delegate.

    override func viewDidLoad() {
            super.viewDidLoad()
    
            quoteTextView.delegate = self
            tableView.estimatedRowHeight = 142
    
        }
    
    1. Add table view delegates for heightForRowAt:
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    1. Conform to UITextViewDelegate to listen when user inputs text.
    extension ViewController: UITextViewDelegate {
        func textViewDidChange(_ textView: UITextView) {
            // Refresh tableView cell
            if textView.numberOfLines > 2 { // textView in storyboard has two lines, so we match the design
                // Animated height update
                DispatchQueue.main.async {
                    self.tableView?.beginUpdates()
                    self.tableView?.endUpdates()
                }
            }
        }
    }
    
    1. Add UITextView extension so you avoid redundant code and use all over the app.
    extension UITextView {
        var numberOfLines: Int {
            // Get number of lines
            let numberOfGlyphs = self.layoutManager.numberOfGlyphs
            var index = 0, numberOfLines = 0
            var lineRange = NSRange(location: NSNotFound, length: 0)
    
            while index < numberOfGlyphs {
                self.layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
              index = NSMaxRange(lineRange)
              numberOfLines += 1
            }
    
            return numberOfLines
        }
    }
    

    -> Do not forgot to disable uitextview scroll. Cheers!<-

    Preview

提交回复
热议问题