【问题标题】:Limiting user's text entry to the height of the UITextView将用户的文本输入限制为 UITextView 的高度
【发布时间】:2015-04-20 15:12:33
【问题描述】:

我正在使用UITextView,并且我想做到这一点,以便一旦用户填写了UITextView(您在情节提要中进行,并且这些尺寸不允许用户在外部输入)用户不能再键入文本。基本上,现在发生的事情是即使它看起来已经填满了,而且我一直在输入它,就像一个你看不到的永无止境的文本框。我假设您在情节提要中制作的尺寸是您在其中看到文本的唯一空间。

有人可以帮我吗?

http://www.prntscr.com/671n1u

【问题讨论】:

  • 好吧,我不确定,我想你到底想表达什么,你想在文本字段中写到某个字符(portan 那是可见的)。你实际上可以做的是,参考这个链接,stackoverflow.com/questions/433337/…

标签: ios swift uitextview


【解决方案1】:

您可以使用UITextViewDelegateshouldChangeTextInRange:方法将文本输入限制在文本视图的高度:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    // Combine the new text with the old
    let combinedText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)

    // Create attributed version of the text
    let attributedText = NSMutableAttributedString(string: combinedText)
    attributedText.addAttribute(NSFontAttributeName, value: textView.font, range: NSMakeRange(0, attributedText.length))

    // Get the padding of the text container
    let padding = textView.textContainer.lineFragmentPadding

    // Create a bounding rect size by subtracting the padding
    // from both sides and allowing for unlimited length 
    let boundingSize = CGSizeMake(textView.frame.size.width - padding * 2, CGFloat.max)

    // Get the bounding rect of the attributed text in the
    // given frame
    let boundingRect = attributedText.boundingRectWithSize(boundingSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)

    // Compare the boundingRect plus the top and bottom padding
    // to the text view height; if the new bounding height would be
    // less than or equal to the text view height, append the text
    if (boundingRect.size.height + padding * 2 <= textView.frame.size.height){
        return true
    }
    else {
        return false
    }
}

【讨论】:

  • 我已经更改了我的代码并实现了该功能,但似乎没有任何改变。然后,我将 UITextViewDelegate 添加到我的课程中,当我运行它时,我因以下错误而崩溃:pastebin.com/3s8v648C - 它似乎不起作用。顺便说一句,当我去那个特定的 VC 时,这会崩溃。这是我的 VC 代码:pastebin.com/7FjYzRnW
  • @wogwog 我向你保证这段代码可以工作......我自己测试过......你需要添加 UITextViewDelegate 并将 UITextView 的委托设置为 self。您能否发布显示您如何尝试添加委托的代码?正如您当前的代码所示,由于您的 viewDidLoad 中没有任何内容,因此一旦您转换到视图,此视图控制器中的任何内容都不会导致崩溃...
  • 好的,我在 viewDidLoad 中添加了:myTextView.delegate = self - 运行它,它仍然崩溃。目前我的课程代码是:class ThirdViewController: UIViewController, UITextViewDelegate {
  • @wogwog 是的,我怀疑你在接口的插座上犯了一个错误:stackoverflow.com/a/13793334/2274694
  • 那么我删除我的 textView 并放置另一个怎么样,那不只是创建一个全新的并解决错误吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
  • 1970-01-01
相关资源
最近更新 更多