【问题标题】:How to not allow typing 'space' in UITextView?如何不允许在 UITextView 中输入“空格”?
【发布时间】:2014-08-16 20:16:23
【问题描述】:

我有一个 UITextView,我不希望用户在输入的文本中有任何空格。我应该怎么做才能不让他使用空格键? 谢谢!

【问题讨论】:

标签: ios objective-c text uitextview


【解决方案1】:

你需要

  1. 将视图控制器指定为文本视图的delegate(您可以通过编程方式执行此操作,也可以在 Interface Builder 中指定委托);和

  2. 你的UITextViewDelegate方法shouldChangeTextInRange需要检查要插入的字符串是否包含空格:

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
        if ([text rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].location != NSNotFound) {
            return NO;
        }
        return YES;
    }
    

    或者,在 Swift 中:

    extension ViewController: UITextViewDelegate {
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            return text.rangeOfCharacter(from: .whitespacesAndNewlines) == nil
        }
    }
    

    注意,这不是检查replacementText 是否等于空格,因为这是不充分的检查。相反,这是检查替换文本内是否出现空格anywhere。这是一个重要的区别,因为可以将文本粘贴到文本视图中,该文本可能不等于空格,但可能在粘贴值的某处包含空格。

【讨论】:

    【解决方案2】:

    我认为正确的做法是首先阻止编辑:

    在您的 ViewController.h 文件中,使其实现 UITextViewDelegate 协议:

    @interface ViewController : UIViewController <UITextViewDelegate>
    

    在 ViewController.m 的 ViewController 的 viewDidLoad 方法中,将 textField 的委托设置为视图控制器:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        self.myTextView.delegate = self;
    }
    

    最后,我们需要在更改发生时捕获更改并删除空格。我们可以在 textViewDidChange: 方法中做到这一点。当新字符串中有空格时,在 shouldChangeTextInRange: 方法中返回 NO 将阻止用户粘贴其中包含空格的文本(可能不是您想要的)。如果我们简单地删除空格,用户就无法从键盘输入新的空格,但如果他们要在剪贴板中使用“hello world”之类的内容进行粘贴,他们会在 TextView 中得到“helloworld”:

    - (void)textViewDidChange:(UITextView *)textView
    {
        // eliminates spaces, including those introduced by autocorrect
        if ([textView.text rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]].location != NSNotFound) {
            textView.text = [textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        }
    }
    

    【讨论】:

      【解决方案3】:

      How does the methods "shouldChangeTextInRange" and "stringByReplacingCharactersInRange" work?

      使用链接中看到的方法(

      - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
       if( [string isEqualToString:@" "] )
          return NO;
       else 
          return YES;
      }
      

      记得设置文本视图的委托

      【讨论】:

        猜你喜欢
        • 2019-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-17
        相关资源
        最近更新 更多