2011-04-26 62 views
0

我想計算用戶輸入的textview中的字符數。我給了它一些想法,我的想法是,我必須創建一個NSTimer與選擇器,檢查長度。 所以我有:計算textview中的字符

-(void)viewDidLoad { [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(checkText) userInfo:nil repeats:YES]; } 

-(void)checkText { 

int characters; 

label.text.length = self.characters; 

characterLabel.text = [NSString stringWithFormat:@"%i", characters]; } 

這不起作用,因爲「在東西不是一個結構或聯合‘’請給成員」字

我怎樣才能解決這個問題?

回答

5

沒有必要的NSTimer。設置自己作爲TextView中的委託和實施:

- (void)textViewDidChange:(UITextView *)textView 
{ 
    NSUInteger length; 
    length = [textView.text length]; 

    characterLabel.text = [NSString stringWithFormat:@"%u", length] 
} 
+0

非常感謝,效果很好 – Leon 2011-04-26 18:13:29

+0

'characterLabel.text = [NSString stringWithFormat:@「%u」,length];'* – user2414460 2013-12-13 10:25:23

0

請注意,如果您嘗試使用self.characters獲取int characters變量的值 - 它將無法使用。 self.characters代碼意味着你有一個屬性設置@property characters,它會調用這個屬性的getter。要使用局部變量只需使用它的名稱。

我想你在-checkText:方法中混用了標籤對象。 下面是如何獲得的字符UITextView的數量一般示例:

int characters = [myTextView.text length]; 
+0

其實這是沒有回答我的問題 – Leon 2011-04-26 10:09:44

+0

我明白了。我已經添加了一些細節,希望你會發現它們有幫助。 – Ziggy 2011-04-26 10:39:46

+1

「在Objective-C中任何方法名稱都包含:符號」 - 這是不對的 – 2011-04-26 10:49:20