*[ 단축키 ]*********************************************
Build : command + B
Build & Run : command + R
Clean : command + Shift + K
document : Shift+Command+Option+?
Research Assistant : Shift+Command+Option+? help > Show Research Assistant
선언 보기 : Command + 마우스 더블클릭
도움말 바로가기 : Option + 마우스 더블클릭
*[ xcode 참조 ]*********************************************
c 언어 *.m
c++ 언어 *.mm
h 헤더 파일을 의미
m 구현 파일을 의미
xib 인터페이스 빌더를 사용하여 만든 사용자 인터페에스 (구 nib에서 xcode 3.0부터 변경됨)
pch 미리 컴파일 된 헤더 파일
plist Xcode 프로젝트 정보가 저장되어 있는 파일
App Sandbox
MyApp.app
Documents - 사용자 데이터를 저장하기 위한 디렉토리
Library - 사용자 데이터가 아닌 파일의 최상위 디렉토리로, iTunes에 의해서 해당 디렉토리의 내용이 백업됨
tmp - 임시 파일들을 저장하기 위한 용도의 디렉토리
*[ 변수 생성 ]*********************************************
BankAccount *account1;
account1 = [BacnAccount alloc];
account1 = [account1 init];
한줄로 생성
BankAccount *account1[[BanckAccount alloc] init];
*[ 데이터 타입 ]*********************************************
int
bool true, false 대신 YES, NO 사용
float 부동소수점 값의 마지막에 f문자를 표기하여 사용
char
*[ Object-C 데이터 타입 ]*********************************************
id 모든 오브젝트들의 참조를 동일한 데이터 타입으로 사용하기 위함
NSInteger C언어의 int (오브젝트 아닌 원시 데이터 타입으로 접근시 포인터를 사용하지 않음)
NSUInteger C언어의 unsigned int
NSString 문자열
*[ 조건문 ]*********************************************
if(조건){
}else if(조건){
}else{
}
switch(index){
case 0:
...
break;
case 1:
...
break;
default
...
break;
}
for(int i=0;i<10;i++){
...
}
for(;;){ //for무한루프
}
while(조건){
}
*[ 인터페이스 및 구현 ]*********************************************
+ 클래스 메서드(반환 값 같은것이 클래스 일경우)
- 인스턴스 메서드(반환 값 같은것이 수식처리에 결과값인 경우)
@interact BankAccount: NSObject
{
//classMember
double accountBalance;
long accountNumber;
}
//classMethod
-(void) setAccount: (long) y andBalance: (double) x;
-(void) setAccountBalance: (double) x;
-(double) getAccountBalance;
//기본적으로 private 이기 때문에 외부 접근을 위해 @property선언
@property double accountBalance;
@property long accountNumber;
@end
@implementation BankAccount
//선언된 프로퍼티들을 연결
@synthesize accountBalance;
@synthesize accountNumber;
-(void) setAccount: (long) y andBalance: (double) x
{
accountBalance = x;
accountNumber = y;
}
-(void) setAccountBalance: (double) x
{
accuntBalance = x;
}
-(double) getAccountBalance
{
return accuntBalance
}
@end
*[ 메소드 호출 ]*********************************************
[오브젝트 메서드명]
[오브젝트 메서드명:값1 인자명:값2]
중첩호출
[오브젝트 메서드명s[오브젝트 메서드명]];
[account1 displayAccountInfo];
[account1 setAccountBalance: 322455];
[account1 setAccount: 322455 andBalance: 23551];
@property int numX;
@synthesize numX;
일경우 기본적으로 setter(set+변수명) 을 사용가능
[오브젝트명 setNumX:3]
*[ 가비지 처리 ]*********************************************
ARC (automatic reference counting) - xcode v4.2
위 옵션 사용시 release,retain,auctorelease,dealloc 사용 금지
Calculator *cal =[[Calculator alloc] init]; //생성
...
[cal release]; //소멸
C++ new delete
Objective-C alloc release
*[ ]*********************************************
*[ ]*********************************************
*[ ]*********************************************
*[ ]*********************************************
*[ Label ]*********************************************
// 폰트 리스트 정의
NSArray *fontList = [[NSArray alloc]
initWithObjects:@"Zapfino", @"GurmukhiMN", @"Verdana",
@"Courier", @"TrebuchetMS", @"AmericanTypewriter",
@"ArialMT", @"Kailasa", @"Helvetica", @"Georgia", nil];
// 레이블 텍스트
[label setText:[NSString stringWithFormat:@"%@", [fontList objectAtIndex:i]]];
// 폰트 적용
label.font = [UIFont fontWithName:[fontList objectAtIndex:i] size:17];
[UIFont fontWithName:폰트이름 size:폰트사이즈]
// 레이블 생성
UILabel *label = [[UILabel alloc] init];
// 배경색 변경
[label setBackgroundColor:[UIColor clearColor]];
// 프레임 설정
[label setFrame:CGRectMake(20, 20+(i*40), 280, 40)];
// 레이블 텍스트
[label setText:[NSString stringWithFormat:@"Using System Font & %dpx", i+10]];
// 폰트 사이즈 변경
label.font = [UIFont systemFontOfSize:i+10];
// 자동 라인 변경 적용 [레이블컨트롤 setNumberOfLines:라인수] 0인경우 자동
[label setNumberOfLines:0];
// 라인 변경 모드 설정
[label setLineBreakMode:i];
// 문자단위 개행
[label setLineBreakMode:UILineBreakModeCharacterWrap];
*[ Button ]*********************************************
CGRect rc = self.view.bounds;
int btnWidth = 70;
int btnHeight = 30;
// 버튼 생성 - RoundedRect
animateBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 프레임 설정
animateBtn.frame = CGRectMake( (rc.size.width - btnWidth)/2,
rc.size.height - btnHeight - 20,
btnWidth,
btnHeight);
// 버튼 타이틀 설정
[animateBtn setTitle:@"Start" forState:UIControlStateNormal];
// 이벤트 타켓 설정
//[버튼컨트롤 addTarget:self action:@selector(엑션메소드) forControlEvents:(이벤트종류)]
[animateBtn addTarget:self action:@selector(startAnimate:)
forControlEvents:UIControlEventTouchUpInside];
// 버튼 배치
[self.view addSubview:animateBtn];
*[ 세그먼트 생성 ]*********************************************
// 타이틀 배열 생성
NSArray *title = [NSArray arrayWithObjects:@"RED",@"GREEN", @"BLUE", @"Test", nil];
// 세그먼트 생성
UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:title];
// 프레임 설정
[segment setFrame:CGRectMake(10, 200, 300, 30)];
// 특정 0번째 비활성화 설정
[segment setEnabled:NO forSegmentAtIndex:0];
[segment setSegmentedControlStyle:UISegmentedControlStyleBar];
[segment2 setSegmentedControlStyle:UISegmentedControlStyleBezeled];
[segment3 setSegmentedControlStyle:UISegmentedControlStyleBordered];
[segment4 setSegmentedControlStyle:UISegmentedControlStylePlain];
// 이벤트 타겟 설정
[segment addTarget:self action:@selector(onSelSegment:) forControlEvents:UIControlEventValueChanged];
//이벤트 처리
- (void)onSelSegment:(id)sender{
UISegmentedControl *segment = (UISegmentedControl *)sender;
// 선택된 인덱스에 따라 처리
switch (segment.selectedSegmentIndex) {
case 0: // RED
[self.view setBackgroundColor:[UIColor redColor]];
break;
case 1: // GREEN
[self.view setBackgroundColor:[UIColor greenColor]];
break;
case 2: // BLUE
[self.view setBackgroundColor:[UIColor blueColor]];
break;
default:
[self.view setBackgroundColor:[UIColor whiteColor]];
break;
}
}
// 세그먼트 이벤트 처리
- (void)onSelSegment:(id)sender{
UISegmentedControl *segment = (UISegmentedControl *)sender;
NSArray *title = [NSArray arrayWithObjects:@"RED",
@"GREEN", @"BLUE", nil];
for ( int i = 0; i < segment.numberOfSegments; i++ ) {
[segment setTitle:[title objectAtIndex:i] forSegmentAtIndex:i];
}
// 선택된 인덱스에 따라 처리
switch (segment.selectedSegmentIndex) {
case 0: // RED
[self.view setBackgroundColor:[UIColor redColor]];
[segment setTitle:@"빨강" forSegmentAtIndex:0]; //타이틀 변경 방법
break;
case 1: // GREEN
[self.view setBackgroundColor:[UIColor greenColor]];
[segment setTitle:@"초록" forSegmentAtIndex:1];
break;
case 2: // BLUE
[self.view setBackgroundColor:[UIColor blueColor]];
[segment setTitle:@"파랑" forSegmentAtIndex:2];
break;
default:
[self.view setBackgroundColor:[UIColor whiteColor]];
break;
}
}
*[ 텍스트 ]*********************************************
// 텍스트 필드 생성
UITextField *text = [[UITextField alloc] initWithFrame: CGRectMake(10, 20, 300, 30)];
// 텍스트 필드 배경색상 변경
[text setBackgroundColor:[UIColor whiteColor]];
// 텍스트 필드 배경색상 변경
text[0].backgroundColor = text[1].backgroundColor
= text[2].backgroundColor = text[3].backgroundColor
= [UIColor whiteColor];
// 레이블 배경색상 변경
label[0].backgroundColor = label[1].backgroundColor
= label[2].backgroundColor = label[3].backgroundColor
= [UIColor clearColor];
// Style None
[label[0] setText:@"Style None"];
[text[0] setBorderStyle:UITextBorderStyleNone];
// Style Line
[label[1] setText:@"Style Line"];
[text[1] setBorderStyle:UITextBorderStyleLine];
// Style Bezel
[label[2] setText:@"Style Bezel"];
[text[2] setBorderStyle:UITextBorderStyleBezel];
// Style Rounded Rect
[label[3] setText:@"Style Rounded Rect"];
[text[3] setBorderStyle:UITextBorderStyleRoundedRect];
[text[3] setPlaceholder:@"UITextBorderStyleRoundedRect"]; //placeholder 작성법
//폰트 설정
// 텍스트필드 폰트 설정
[text[i] setFont:[UIFont fontWithName:@"Times New Roman" size:20-i*3]];
// 배경색 변경
text[i].backgroundColor = [UIColor whiteColor];
// 텍스트 필드 문자 색상 세팅
UIColor *textColor;
textColor = [UIColor blueColor];
[text[i] setTextColor:textColor];
//정렬
UITextAlignment textAlign;
textAlign = UITextAlignmentLeft;
textAlign = UITextAlignmentCenter;
textAlign = UITextAlignmentRight;
[text[i] setTextAlignment:textAlign];
[label setTextAlignment:UITextAlignmentRight];
//키보드 타입
// 자동 폰트 설정
[text[i] setAdjustsFontSizeToFitWidth:YES];
// 키보드 타입 설정
[text[i] setKeyboardType:i+1];
labelText = @"ASCIICapable";
labelText = @"NumbersAndPunc";
labelText = @"URL";
labelText = @"NumberPad";
labelText = @"PhonePad";
labelText = @"NamePhonePad";
labelText = @"EmailAddress";
labelText = @"DecimalPad";
labelText = @"Twitter";
// 델리게이트 설정
[text[i] setDelegate:(id)self];
// Clear 버튼 설정
[text[i] setClearButtonMode:UITextFieldViewModeWhileEditing];
//아래 함수를 재정의해서 이벤트를 캡쳐함
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField; // return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField; // became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField; // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (void)textFieldDidEndEditing:(UITextField *)textField; // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
- (BOOL)textFieldShouldClear:(UITextField *)textField; // called when clear button pressed. return NO to ignore (no notifications)
- (BOOL)textFieldShouldReturn:(UITextField *)textField; // called when 'return' key pressed. return NO to ignore.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// NO를 반환하면 키보드 입력이 허락되지 않는다. 필요에 따라서 적절히 사용가능
NSLog(@"textFieldShouldBeginEditing");
return YES;
}
// became first responder
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
// 입력된 텍스트를 디버그 창에 출력
NSLog(@"%@", [NSString stringWithFormat:@"%@ \"%@\"",
@"textFieldDidBeginEditing >>> ",
textField.text]);
}
// return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
NSLog(@"textFieldShouldEndEditing");
return YES;
}
// may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSLog(@"textFieldDidEndEditing");
}
// return NO to not change text
// NO 반환 시 텍스트 변경이 되지 않음
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(@"%@", [NSString stringWithFormat:
@"\n[shouldChangeCharactersInRange]\n"
"\tOld string: \'%@\'\n"
"\tInput string: \'%@\'\n"
"\tRange:(%d,%d)",
textField.text,
string,
range.location,
range.length
]);
return YES;
}
// called when clear button pressed. return NO to ignore (no notifications)
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
NSLog(@"textFieldShouldClear");
return YES;
}
// called when 'return' key pressed. return NO to ignore.
// return/done 버튼이 필요
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSLog(@"textFieldShouldReturn");
// 키보드 감춤
[textField resignFirstResponder];
return YES;
}
//입력 값 검토
// 텍스트필드 고유아이디 정의
enum
{
TXFILED_USER_ID = 1 ,
TXFILED_USER_PW,
TXFILED_USER_AGE
};
[textID setDelegate:(id)self];
[textID setTag:TXFILED_USER_ID];
[textPW setTag:TXFILED_USER_PW];
[textAge setTag:TXFILED_USER_AGE];
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
BOOL bRet = YES;
// Number formatter
NSNumberFormatter *number;
switch (textField.tag) {
case TXFILED_USER_PW: // 패스워드 입력 창
// 입력 위치 검토
if(range.location > 11)
{
bRet = NO;
}
break;
case TXFILED_USER_AGE:
// 입력 위치 검토: 999살 넘는 사람은 없으므로...
if(range.location > 2)
{
bRet = NO;
}
// 숫자검토
number = [[NSNumberFormatter alloc] init];
[number setNumberStyle:NSNumberFormatterDecimalStyle];
if( ![number numberFromString:string] )
{
bRet = NO;
}
break;
default:
break;
}
return bRet;
}
//컨트롤이 키보드 아래 나타나는 문제를 해결 하기 위한 방법
//포커스가 올? 화면을 위로 올렸다 , 포커스가 나갈때 화면을 돌리는 방향
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect viewFrame;
switch (textField.tag) {
case TXFILED_USER_AGE:
// 현재 뷰의 프레임을 획득
viewFrame = self.view.frame;
// y축 기준점을 감소
viewFrame.origin.y -= 100;
// 에니메이션 효과 적용
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.5f];
// 변경된 프레임 적용
[self.view setFrame:viewFrame];
[UIView commitAnimations];
break;
default:
break;
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
// 키보드 감춤
[textField resignFirstResponder];
CGRect viewFrame;
switch (textField.tag) {
case TXFILED_USER_AGE:
// 현재 뷰의 프레임을 획득
viewFrame = self.view.frame;
// y축 기준점을 증가
viewFrame.origin.y += 100;
// 에니메이션 효과 적용
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.5f];
// 변경된 프레임 적용
[self.view setFrame:viewFrame];
[UIView commitAnimations];
break;
default:
break;
}
return YES;
}
*[ 슬라이더 ]*********************************************
// 슬라이더 생성
UISlider *slider = [[UISlider alloc] initWithFrame: CGRectMake(0, 0, 300, 30)];
// 뷰의 중앙으로 위치 변경
[slider setCenter:self.view.center];
// 이벤트 타켓 설정
[slider addTarget:self action:@selector(releaseSlide:) forControlEvents:UIControlEventTouchUpInside];
// TouchUpInside Event
- (void)releaseSlide:(id)sender
{
// 슬라이더 포인터로 typecast
UISlider *slider = (UISlider*)sender;
// 레이블에 슬라이더 값을 출력
[label1 setText:[NSString stringWithFormat:@"%f", slider.value]];
}
// 최대값 설정
[slideRed setMaximumValue:255.0];
[slideGreen setMaximumValue:255.0];
[slideBlue setMaximumValue:255.0];
//슬라이더 이벤트에 따라 배경색 변경
[self.view setBackgroundColor: RGB(slideRed.value, slideGreen.value, slideBlue.value)];
// 세로 슬라이드
// 시계 방향으로 90도 회전
CGAffineTransform trans = CGAffineTransformMakeRotation(90 * M_PI/180);
slideGreen.transform = trans;
// 시계 반대 방향으로 90도 회전
trans = CGAffineTransformMakeRotation(-90 * M_PI/180);
slideBlue.transform = trans;
// 슬라이더 손잡이 색깔
// tintColor for thumbs
[slideRed setThumbTintColor:[UIColor redColor]];
[slideGreen setThumbTintColor:[UIColor greenColor]];
[slideBlue setThumbTintColor:[UIColor blueColor]];
//슬라이더 게이지 색깔
// tintColor for minimum tracks
[slideRed setMinimumTrackTintColor:[UIColor redColor]];
[slideGreen setMinimumTrackTintColor:[UIColor greenColor]];
[slideBlue setMinimumTrackTintColor:[UIColor blueColor]];
*[ 스위치 ]*********************************************
// 스위치 생성
UISwitch *sw = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
// 위치 변경
[sw setCenter:self.view.center];
// 이벤트 타겟 설정
[switchItem addTarget:self action:@selector(saveState:) forControlEvents:UIControlEventValueChanged];
[switchItem setOn:YES];
[switchItem setOn:NO];
int nSelected = [[userInfo objectForKey:@"State_Switch"] intValue];
// 사용자 데이터 적용 (on/off)
if ( nSelected & switchItem.tag ) {// ON
[switchItem setOn:YES];
} else {// OFF
[switchItem setOn:NO];
}
- (void)saveState:(id)sender
{
int nState = 0;
// 사용자 데이터 로드
NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
nState = [[userInfo objectForKey:@"State_Switch"] intValue];
// UISwitch 포인터로 type cast
UISwitch *item = (UISwitch*)sender;
if ( [item isOn] ) // switch on
{
if ( !(nState & item.tag) )
nState += item.tag;
}
else // switch off
{
if ( nState & item.tag )
nState -= item.tag;
}
// 사용자 데이터 저장
[userInfo setValue:[NSString stringWithFormat:@"%d", nState] forKey:@"State_Switch"];
}
// ON OFF 텍스트 변경
[self setSwitchTitle:sw2 offString:@"NO" onString:@"YES"];
// 색상 변경 Tint Color
[sw2 setOnTintColor:[UIColor orangeColor]];
// On Tint Color
[sw2 setOnTintColor:[UIColor greenColor]];
//Off Tint Color
[sw2 setTintColor:[UIColor redColor]];
// Thumb Tint Color
[sw2 setThumbTintColor:[UIColor yellowColor]];
// On Image 적용
[sw3 setOnImage:[UIImage imageNamed:@"buttonOn.png"]];
// Off Image 적용
[sw3 setOffImage:[UIImage imageNamed:@"buttonOff.png"]];
*[ 스핀너 ]*********************************************
// 영역을 설정하여 초기화
spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
// 뷰의 중앙으로 위치 변경
spinner.center = self.view.center;
// 뷰에 배치
[self.view addSubview:spinner];
[spinner startAnimating];
[spinner stopAnimating];
//각 스타일별 스핀너
// UIActivityIndicatorViewStyleGray
spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.center = CGPointMake(160, 50);
// UIActivityIndicatorViewStyleWhite
spinner2 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
spinner2.center = CGPointMake(160, 150);
// UIActivityIndicatorViewStyleWhiteLarge
spinner3 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner3.center = CGPointMake(160, 250);
// 빨간색으로 변경
[spinner setColor:[UIColor redColor]];
// 상태바에 스피너 시작
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
// 상태바의 스피너 정지
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
*[ 프로그래스 ]*********************************************
// 프로그래스 생성
UIProgressView *prog = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
// 프레임 설정
[prog setFrame:CGRectMake(20, 100, 280, 15)];
// 뷰에 배치
prog.center = self.view.center;
// 위치만 이동
[progress setProgress:0.8f];
// 애니메이션 적용 (iOS 5.0)
[progress setProgress:0.2f animated:YES];
// 스테퍼 추가
UIStepper *step = [[UIStepper alloc] initWithFrame:CGRectMake(120, 250, 0, 0)];
[step addTarget:self action:@selector(stepProc:) forControlEvents:UIControlEventTouchUpInside];
// 최대값 설정
[step setMaximumValue:1.0f];
// 최소값 설정
[step setMinimumValue:0.0f];
// 증감 값 설정
[step setStepValue:0.2f];
// 스테퍼를 프로그래스에 연결 방법
- (void)stepProc:(id)sender
{
// 스태퍼인 경우
UIStepper *step = (UIStepper*)sender;
// 위치 변경
[progress setProgress:step.value animated:YES];
}
// 기본 스타일
UIProgressView *prog = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
// 바 스타일
UIProgressView *prog2 = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
// Prgress TintColor
[progTint setProgressTintColor:[UIColor redColor]];
// Track TintColor
[trackTint setProgressTintColor:[UIColor grayColor]];
[trackTint setTrackTintColor:[UIColor lightGrayColor]];
// Custom Image
[imageProg setTrackImage:[UIImage imageNamed:@"track.png"]];
[imageProg setProgressImage:[UIImage imageNamed:@"progress.png"]];
*[ 경고창 ]*********************************************
// AlertView 생성
UIAlertView * alert = [[UIAlertView alloc]
initWithTitle:@"AlertView" // 제목
message:@"Hello, UIAlertView!" // 본문
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
// 화면에 출력
[alert show];
// AlertView 생성
UIAlertView * alert = [[UIAlertView alloc]
initWithTitle:@"AlertView"
message:@"Hello, UIAlertView!"
delegate:nil
cancelButtonTitle:@"OK"
// 추가하고자 하는 버튼의 타이틀들을 입력
otherButtonTitles:@"Cancel", nil];
// 화면에 출력
[alert show];
// AlertView 생성
alert = [[UIAlertView alloc]
initWithTitle:@"Choose Color"
message:@"What is your favorite color?"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:nil];
// 델리게이트 설정
[alert setDelegate:self];
- (void)addButton:(id)sender
{
// 버튼이 추가되지 않은 경우에만 처리
if ( alert.numberOfButtons < 2 )
{
// 버튼에 출력될 문자열
NSArray *colors = [NSArray arrayWithObjects:@"Red", @"Green", @"Blue", @"Black", nil];
// 버튼 추가
for ( int i = 0; i < [colors count]; i++ )
{
[alert addButtonWithTitle:[colors objectAtIndex:i]];
}
}
// 화면에 출력
[alert show];
}
// 버튼 클릭 이벤트가 발생하면 호출
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
// 버튼에 맞는 색상으로 뷰를 설정
switch (buttonIndex) {
case 1: // Red
[self.view setBackgroundColor:[UIColor redColor]];
break;
case 2: // Green
[self.view setBackgroundColor:[UIColor greenColor]];
break;
case 3: // Blue
[self.view setBackgroundColor:[UIColor blueColor]];
break;
case 4: // Black
[self.view setBackgroundColor:[UIColor blackColor]];
break;
default:
break;
}
}
// 버튼 이벤트 처리
- (void)showAlertView:(id)sender
{
// 타입 케스트
UIButton *btn = (UIButton*)sender;
//btnDefault.tag = 1; 이전에 이와 같은 방식으로 tag 값을 설정함.
switch (btn.tag) {
case 1: // Default style
alert = [[UIAlertView alloc]
initWithTitle:@"DefaultStyle"
message:nil
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
break;
case 2: // SecureText Style
alert = [[UIAlertView alloc]
initWithTitle:@"SecureTextStyle"
message:@"Enter secure text."
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
alert.alertViewStyle = UIAlertViewStyleSecureTextInput;
break;
case 3: // PlainText Style
alert = [[UIAlertView alloc]
initWithTitle:@"PlainTextStyle"
message:@"Enter plain text"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
break;
case 4: // LoginAndPasword Style
alert = [[UIAlertView alloc]
initWithTitle:@"LoginAndPaswordStyle"
message:@"Enter user id & password"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
break;
}
// 알림 창의 태그 설정
alert.tag = btn.tag;
// 화면에 출력
[alert show];
}
// 버튼 클릭 이벤트가 발생하면 호출
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
// 태그를 사용하여 스타일에 따른 처리
switch (alertView.tag) {
case 1: // DefaultStyle
NSLog(@"DefaultStyle Alert!");
break;
case 2: // SecureTextStyle
NSLog(@"SecureTextStyle - Input String: %@",
[alertView textFieldAtIndex:0].text);
break;
case 3: // PlainTextStyle
NSLog(@"PlainTextStyle - Input String: %@",
[alertView textFieldAtIndex:0].text);
break;
case 4: // LoginAndPaswordStyle
NSLog(@"LoginAndPaswordStyle - ID: %@, PW: %@",
[alertView textFieldAtIndex:0].text,
[alertView textFieldAtIndex:1].text);
break;
default:
break;
}
}
*[ 테이블 뷰 ]*********************************************
section
row
numberOfSectionsInTableView : 테이블 뷰에 출력할 Section의 수를 반환
numberOfRowsInSection : 해당 Section에 포함될 Row의 수를 반환
cellForRowAtIndexPath : 해당 Section과 Row에 해당하는 테이블 뷰 셀을 작성하여 반환
didSelectRowAtIndexPath : 선택시 작동할 액션 처리 메서드
//데이터를 로드하는 절차
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#ifdef STYLE_PLAIN
// 배열에 저장된 색상 갯수를 리턴
return [colors count];
#endif
return 1;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
// 셀의 스타일을 변경
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
// 액세서리 뷰를 다르게 표현
switch (indexPath.row % 3) {
case 0:
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
break;
case 1:
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
break;
case 2:
cell.accessoryType = UITableViewCellAccessoryCheckmark;
break;
}
}
#ifdef STYLE_PLAIN
// 배열에 저장된 텍스트를 셀의 텍스트에 적용
cell.textLabel.text = [colors objectAtIndex:indexPath.row];
#ifdef USE_SUBTITLE
// 서브 타이틀 설정
cell.detailTextLabel.text = [kcolors objectAtIndex:indexPath.row];
#endif
#ifdef USE_IMAGE
// 셀에 이미지를 추가
cell.imageView.image = [UIImage imageNamed:
[images objectAtIndex:indexPath.row]];
#endif
return cell;
#endif
// Configure the cell.
cell.textLabel.text = NSLocalizedString(@"Detail", @"Detail");
return cell;
}
//Row를 선택시 이벤트 메서드
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (!self.detailViewController) {
self.detailViewController =
[[DetailViewController alloc]
initWithNibName:@"DetailViewController" bundle:nil];
}
#ifdef STYLE_PLAIN
// 배경색 설정
switch (indexPath.row) {
case 0:
[self.detailViewController.view
setBackgroundColor:[UIColor redColor]];
break;
case 1:
[self.detailViewController.view
setBackgroundColor:[UIColor greenColor]];
break;
case 2:
[self.detailViewController.view
setBackgroundColor:[UIColor blueColor]];
break;
case 3:
[self.detailViewController.view
setBackgroundColor:[UIColor brownColor]];
break;
case 4:
[self.detailViewController.view
setBackgroundColor:[UIColor grayColor]];
break;
default:
[self.detailViewController.view
setBackgroundColor:[UIColor whiteColor]];
break;
}
// 네비게이션 타이틀 적용
[self.detailViewController setTitle:[colors objectAtIndex:indexPath.row]];
#endif
[self.navigationController pushViewController:self.detailViewController animated:YES];
}
*[ ]*********************************************
*[ ]*********************************************
*[ ]*********************************************
*[ ]*********************************************
*[ ]*********************************************
*[ ]*********************************************