iphone - 如何在 UITextView 中实现简单的 'live' 字数统计

标签 iphone objective-c cocoa-touch uitextview

我正在尝试在用户输入文本时实现 UITextView 的简单字符计数(即它应该持续更新)。

我有两个问题。

(1) 首先是我不知道应该把我的charCount 方法放在哪个方法中。 textViewShouldBeginEditing 不起作用,因为它只是询问是否应开始编辑 session 。 textView:shouldChangeTextInRange 也不起作用,因为它再次询问是否允许开始编辑。我在 Apple 文档中找不到其他有用的方法。

(2) 下一个问题:我试图从另一个方法中调用我的 charCount 方法。但我收到编译器错误:“ViewController”可能无法响应“charCount”。

这是我的拙劣尝试:

- (IBAction)charCount:(id)sender {

// all chars
int charsAsInt = (int)(textView.text.length);
NSString *newText = [[NSString alloc] initWithFormat:@"All chars: %d", charsAsInt];
allCharacters.text = newText;
[newText release];}

- (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView {

    [self charCount];}

我想这与我尝试调用 IBAction 定义的方法有关,但它不起作用。但是从非 IBAction 方法中调用 IBAction 方法的正确方法是什么?

一如既往,对于这些非常基本的问题,我深表歉意,我非常感谢能帮助我的初学者解决这个问题的每一点帮助。

最佳答案

我以前是这样创建的,为了防止UITextview只输入140个字符。
我像这样在 UILabel 中显示了计数

-(void)textViewDidChange:(UITextView *)textView 
{
   int len = textView.text.length;
   lbl_count.text=[NSString stringWithFormat:@"%i",140-len];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text length] == 0)
    {
        if([textView.text length] != 0)
        {
            return YES;
        }
    }
    else if([[textView text] length] > 139)
    {
        return NO;
    }
    return YES;
} 

这可能对你有帮助!!!

关于iphone - 如何在 UITextView 中实现简单的 'live' 字数统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5258416/

相关文章:

iphone - 我需要 UINavigationController 吗?

iphone - 调整大型 UITable 的大小会使应用程序停止运行

iphone - 如何确定 UICollectionView flowLayout 中单元格之间的间距

iphone - 为什么我的 View 类没有出现在故事​​板中?

ios - 检测是否在 iOS 7 上设置了 Twitter 帐户

ios - NSTimer 不会将参数传递给选择器

iphone - 使用exportAsynchronouslyWithCompletionHandler

iphone - 如何获取旧版 SDK?我是否需要?

ios - 根据Objc中的条件添加或删除uiview?

cocoa-touch - UITableView 之外的 UITableViewCell