▼iPhoneプログラミングメモ▼
テキストフィールド

テキストフィールドを利用するプログラムを作成する。


ソースコードの記述
TextFieldEx.h
#import UIKit/UIKit.h

//TextFieldExの宣言
@interface TextFieldEx : UIViewController<UITextFieldDelegate> {
    UITextField* _textField;
}
@end

TextFieldEx.m
#import "TextFieldEx.h"

#define BTN_SHOW 0

//TextFieldExの実装
@implementation TextFieldEx

//アラートの表示
- (void)showAlert:(NSString*)title text:(NSString*)text {
    UIAlertView* alert=[[[UIAlertView alloc] 
        initWithTitle:title message:text delegate:nil 
        cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
    [alert show];
}

//テキストフィールドの生成
- (UITextField*)makeTextField:(CGRect)rect text:(NSString*)text {
    UITextField* textField=[[[UITextField alloc] init] autorelease];
    [textField setFrame:rect];
    [textField setText:text];
    [textField setBackgroundColor:[UIColor whiteColor]];
    [textField setBorderStyle:UITextBorderStyleRoundedRect];
    [textField setKeyboardAppearance:UIKeyboardAppearanceDefault];        
    [textField setKeyboardType:UIKeyboardTypeDefault];
    [textField setReturnKeyType:UIReturnKeyDone];
    return textField;
}

//テキストボタンの生成
- (UIButton*)makeButton:(CGRect)rect text:(NSString*)text tag:(int)tag {
    UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:rect];
    [button setTitle:text forState:UIControlStateNormal];
    [button setTag:tag];
    [button addTarget:self action:@selector(clickButton:) 
        forControlEvents:UIControlEventTouchUpInside];
    return button;
}

//初期化
- (void)viewDidLoad {
    [super viewDidLoad];
        
    //テキストフィールドの生成
    _textField=[[self makeTextField:CGRectMake(0,0,300,32) 
        text:@""] retain];
    [_textField setDelegate:self];
    [self.view addSubview:_textField];
        
    //ボタンの生成
    UIButton* btnShow=[self makeButton:CGRectMake(0,50,90,40) 
        text:@"表示" tag:BTN_SHOW];
    [self.view addSubview:btnShow];
}

//メモリ解放
- (void)dealloc {
    [_textField release];
    [super dealloc];
}

//改行ボタン押下時に呼ばれる
- (BOOL)textFieldShouldReturn:(UITextField*)sender {
    //ソフトウェアキーボードの表示・非表示
    [sender resignFirstResponder];
    return YES;
}

//テキスト変更時に呼ばれる
- (BOOL)textField:(UITextField*)textField 
    shouldChangeCharactersInRange:(NSRange)range 
    replacementString:(NSString*)text {
    //最大140文字制限
    if (text.length>0 &&
        textField.text.length+text.length>140) {
         return NO;
    }
    return YES;
}

//ボタンクリック時に呼ばれる
- (IBAction)clickButton:(UIButton*)sender {
    if (sender.tag==BTN_SHOW) {
        [self showAlert:@"" text:[NSString stringWithFormat:
            @"テキストフィールドの文字列\n%@",_textField.text]];
    }
}

//画面を端末の向きにあわせて回転
- (BOOL)shouldAutorotateToInterfaceOrientation:
    (UIInterfaceOrientation)orientation {
    return YES;
}
@end



−戻る−