月曜日までに考えておきます

ITネタとゲームネタ中心に興味のあること色々書きます。

iOSで入力文字数をカウントするテキスト入力画面の作り方

最近、iOSのアプリ開発を勉強しつつやってたのでそれについての記事など。 Twitterアプリとかでよくある、入力文字数に応じて残りの入力文字数の表示を減らしていく、という機能。 よくある機能ですが作るのにちょいコツが必要でした。 こんなの↓ th_写真 12-07-15 21 44 24 ■手順です 1.StoryBoard(InterfaceBuilder)で、TextViewと、Labelが載ったViewを作る。 th_SampleTextView.xcodeproj — MainStoryboard.storyboard 2.ViewController.h
#import 
#define MAX_LENGTH 140
@interface ViewController : UIViewController
@property IBOutlet UITextView *inputTextView;
@property IBOutlet UIView *optionView;
@property IBOutlet UILabel *countLabel;
@end
みたいな感じ。 3.ViewController.m
@synthesize inputTextView, optionView, countLabel;
 
- (void)viewDidLoad
{
    [superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    [inputTextViewbecomeFirstResponder];
    inputTextView.inputAccessoryView = optionView;
    inputTextView.delegate = self;
}
と、ここまでやって、あとはTextViewにIBActionで定義したメソッドを繋いだらTextChanged、みたいなイベント出るだろ、と思ったら見つからなくて焦った(;´Д`) どうやらTextViewのときはDelegateを使う必要があるらしい。 というわけで 4.ViewController.hにDelegateを定義
@interface ViewController : UIViewController
5.ViewController.mに以下の内容を記述
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    int textCount = textView.text.length + text.length - range.length;
    int remain = MAX_LENGTH - textCount;
    if (remain < 0) {
        countLabel.textColor=[UIColor redColor];
    }else{
        countLabel.textColor=[UIColor blackColor];
    }
    countLabel.text = [NSString stringWithFormat:@"%d", remain];
    return YES;
}
でこんな機能ができます。 th_iOSシミュレータ 一画面作って、モーダルで呼び出すようにしてDelegateで呼び出し元にテキストを返すようにすれば汎用的に使えるんじゃないかと思います。