【问题标题】:Set max lines editable TextView - Swift/iOS设置最大行数可编辑 TextView - Swift/iOS
【发布时间】:2017-06-25 20:38:16
【问题描述】:

以下代码将设置 TextView 的最大行数。

textView.textContainer.maximumNumberOfLines = 5;
textView.textContainer.lineBreakMode = .byTruncatingTail

但是,在编辑模式下,您可以在超出最大行数后继续按 Enter 键并在屏幕上键入。

如果您尝试输入更多内容,如何使光标不会转到下一行?

【问题讨论】:

    标签: ios swift uitextview


    【解决方案1】:

    试试这个

    func sizeOfString (string: String, constrainedToWidth width: Double, font: UIFont) -> CGSize {
        return (string as NSString).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin,
            attributes: [NSFontAttributeName: font],
            context: nil).size
    }
    
    
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
        var textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset))
        textWidth -= 5.0 * textView.textContainer.lineFragmentPadding;
    
        let boundingRect = sizeOfString(newText, constrainedToWidth: Double(textWidth), font: textView.font!)
        let numberOfLines = boundingRect.height / textView.font!.lineHeight;
    
        return numberOfLines <= 5;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 2016-02-06
      • 1970-01-01
      • 2013-05-01
      相关资源
      最近更新 更多