将字数限制应用于UITextView [英] Applying a Word Limit to a UITextView

查看:31
本文介绍了将字数限制应用于UITextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Objective-C/界面构建器中将字数限制应用于UITextView ??

How is it possible to apply a word limit to a UITextView in objective-c/interface builder.?

我已经搜索了一段时间,却发现字符数而不是字数...

I have been searching for a while and have found character count but not word count...

谁能给我任何指点...

Cany anybody give me any pointers...

推荐答案

您可以只计算空格数并加以限制.这是一个hack,但是可以.

You can just count the number of spaces and restrict that. It's a hack, but it works.

您可以在内部完成

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText

使用这些NSString方法之一

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

例如,您可以按照以下步骤进行操作:

For example, you can do something along these lines:

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText {
        NSString* newText = [aTextView.text stringByReplacingCharactersInRange:aRange withString:aText];
        NSString *trimmedText = [newText stringByReplacingOccurrencesOfString:@" " withString:@""];

        if (newText.length - trimmedText.length > wordLimit) {
            return NO;
        } else {
            return YES;
        }
}

如果您想更加准确,也可以先固定"文本,方法是用单个空格替换多个空格,并在标点符号后插入一个空格.可能应该将其编写为您在输入文本上调用的单独函数.

If you want to be more accurate, you can also "fix" the text first by replacing multiple spaces with a single space and inserting a space after punctuation. This should probably be written as a separate function that you call on the input text.

这篇关于将字数限制应用于UITextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆