posted by 프띠버리 2013. 9. 13. 16:56

TableViewController.h


#import <UIKit/UIKit.h>


@interface TableViewController : UITableViewController<UITableViewDataSource, UITableViewDelegate>

{

    NSArray *products;

}



@end




TableViewController.m


#import "TableViewController.h"


@interface TableViewController ()


@end


@implementation TableViewController

#define ITEM_NAME @"ITEM_NAME"

#define ITEM_PRICE @"ITEM_PRICE"

#define ITEM_PIC @"ITEM_PIC"

#define ITEM_ID @"ITEM_ID"


- (id)initWithStyle:(UITableViewStyle)style

{

    self = [super initWithStyle:style];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

/*

    products = [[NSArray alloc] initWithObjects:

                [NSDictionary dictionaryWithObjectsAndKeys:@"0", ITEM_ID, @"iPAD", ITEM_NAME, @"699$", ITEM_PRICE, @"ipad2.jpg", ITEM_PIC, nil],

                [NSDictionary dictionaryWithObjectsAndKeys:@"1", ITEM_ID, @"iMAC", ITEM_NAME, @"1199$", ITEM_PRICE, @"imac.jpg", ITEM_PIC, nil],

                [NSDictionary dictionaryWithObjectsAndKeys:@"2", ITEM_ID, @"iPhone", ITEM_NAME, @"699$", ITEM_PRICE, @"iphone.jpg", ITEM_PIC, nil],

                [NSDictionary dictionaryWithObjectsAndKeys:@"3", ITEM_ID, @"MacBook", ITEM_NAME, @"699$", ITEM_PRICE, @"macbook.jpg", ITEM_PIC, nil],

                [NSDictionary dictionaryWithObjectsAndKeys:@"4", ITEM_ID, @"iPAD Nano", ITEM_NAME, @"149$", ITEM_PRICE, @"nano.jpg", ITEM_PIC, nil],

                nil];

 */

    products = @[@{ITEM_ID:@"0", ITEM_NAME:@"iPad", ITEM_PRICE:@"699$", ITEM_PIC:@"ipad2.jpg"},

                 @{ITEM_ID:@"1", ITEM_NAME:@"iMAC", ITEM_PRICE:@"1199$", ITEM_PIC:@"imac.jpg"},

                 @{ITEM_ID:@"2", ITEM_NAME:@"iPhone", ITEM_PRICE:@"699$", ITEM_PIC:@"iphone.jpg"},

                 @{ITEM_ID:@"3", ITEM_NAME:@"MacBook", ITEM_PRICE:@"999$", ITEM_PIC:@"macbook.jpg"},

                 @{ITEM_ID:@"4", ITEM_NAME:@"iPad Nano", ITEM_PRICE:@"149$", ITEM_PIC:@"nano.jpg"}];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    // Return the number of sections.

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    // Return the number of rows in the section.

    return [products count];

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    

    // Configure the cell...

    if(cell==nil)

    {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    NSDictionary *productInfo=[products objectAtIndex:indexPath.row];

    NSString *name=[productInfo objectForKey:ITEM_NAME];

    NSString *price=[productInfo objectForKey:ITEM_PRICE];

    NSString *pic=[productInfo objectForKey:ITEM_PIC];

    

    UIImageView *picView=(UIImageView *)[cell viewWithTag:100];

    picView.image = [UIImage imageNamed:pic];

    

    UILabel *nameLabel=(UILabel *)[cell viewWithTag:200];

    nameLabel.text = name;

    

    UILabel *priceLabel = (UILabel *)[cell viewWithTag:300];

    priceLabel.text = price;

    

    return cell;

}



@end



TablePrice4.zip


posted by 프띠버리 2013. 9. 11. 06:54

 

 

ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate>

{

    // 텍스트 필드 변수 선언

    IBOutlet UITextField *contextTextField;

    // 테이블용 변수 선언

    IBOutlet UITableView *table;

    // 유동성 배열 변수 선언

    NSMutableArray *data;

    // url저장할 문자열 변수 선언

    NSString *urlStr;

}

// 웹뷰용 변수 선언

@property (weak, nonatomic) IBOutlet UIWebView *webView;

 

// 테이블에 셀의 내용 추가할 메소드
- (IBAction)addItem:(id)sender;

// 테이블 수정 모드로 전환할때 메소드

- (IBAction)toggleEditMode:(id)sender;



@end



ViewController.m

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController

// 섹션구분을 위해 CELL_ID란 이름을 정의

#define CELL_ID @"CELL_ID"

 

// 테이블의 섹션 개수

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    // 섹션 개수는 1개

    return 1;

}

 

// 테이블 섹션의 셀 개수

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    // 셀 개수는 data라는 배열안의 개수 만큼 표시

    return [data count];

}

 

// 테이블의 내용이 있는 셀을 선택했을때
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    // urlStr이라는 문자열 변수에 현재 선택한 셀의 텍스트를 저장한다.

    urlStr = [data objectAtIndex:indexPath.row];

    NSLog(@"%@", urlStr);

    // url형식을 가지는 변수에 urlStr의 내용을 넣어서 웹뷰에서 쓸수 있게 한다.

    NSURL *url = [NSURL URLWithString:urlStr];

    // 웹뷰의 URL에 url변수의 주소를 집어 넣음

    NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];

    // 웹뷰에 현재 url이 가리키는 주소의 웹페이지를 화면에 보여준다.

    [self.webView loadRequest:requestURL];

    

}

 

// 테이블 셀 안에 내용 집어넣기

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    // cell은 CELL_ID라는 이름을 가지는 테이블 셀형식이다.

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_ID];

    // 표시할 내용을 가진 셀이 없으면

    if(nil == cell)

    {

        // cell은 CELL_ID라는 이름을 가진 기본 형태의 셀로 초기화됨

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_ID];

    }

    // 각 셀의 텍스는 data라는 배열안의 내용을 넣어준다. 

    cell.textLabel.text = [data objectAtIndex:indexPath.row];

    // 셀을 반환하여 각 셀이 내용을 가지게 된다.

    return cell;

}


// 수정

- (void)tableView:(UITableView *)tableview commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

    // 테이블이 수정(셀 지우기) 모드일때

    if(editingStyle == UITableViewCellEditingStyleDelete)

    {

        // data배열에서 현재 선택된 셀의 내용을 지움

        [data removeObjectAtIndex:indexPath.row];

        // 테이블 다시 보여주기

        [table reloadData];

    }

}


// 이동

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

{

    // 셀이 하나 지워지면 위치를 이동한다.

    return YES;

}


// 이동 -> 데이터 적용(좀더 이해가 필요함)

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath

{

    // 오브젝트형 obj변수에 data 배열의 현재 선택된 부분 저장

    NSObject *obj = [data objectAtIndex:sourceIndexPath.row];

    // data 배열에서 현재 선택된 부분 삭제

    [data removeObjectAtIndex:sourceIndexPath.row];

    // data 배열에 obj에 저장된 내용을 삽입

    [data insertObject:obj atIndex:destinationIndexPath.row];

    NSLog(@"data : %@", data);

}


// 키보드

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    // 기본적으로 프로그램이 실행되면 포커스는 텍스트 필드에 맞춰짐

    [textField resignFirstResponder];

    // additem메소드 호출

    [self addItem:nil];

    // 키패드 자동으로 내려가기

    return YES;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    // 웹뷰 델리게이트

    self.webView.delegate = self;

    // 텍스트필드 델리게이트

    contextTextField.delegate = self;

    // data를 유동형 배열로 초기화

    data = [[NSMutableArray alloc] init];

}


// 데이터 추가

- (IBAction)addItem:(id)sender

{

    // 문자열 변수 inputStr은 현재 입력된 텍스트 필드의 내용을 저장한다.

    NSString *inputStr = contextTextField.text;

    // inputStr 문자열의 길이가 0 보다 클때만(즉, 하나의 내용이라도 들어가 있을때만)

    if([inputStr length] > 0)

    {

        // data 배열에 현재 택스트 필드에 입력했던 내용을 추가

        [data addObject:inputStr];

        // 테이블 다시보여주기

        [table reloadData];

        // 텍스프 필드 공란으로 초기화

        contextTextField.text = @"";

    }

}


// 편집/완료 상태 토글식 동작

- (IBAction)toggleEditMode:(id)sender

{

    // 테이블이 수정모드면 비수정 상태로

    table.editing = !table.editing;

    // 버튼의 제목은 수정모드일때 Done를 표시 아니면 Edit를 표시

    ((UIBarButtonItem *)sender).title = table.editing ? @"Done" : @"Edit";

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




 

'Programing > IOS' 카테고리의 다른 글

뷰티 오브 코리아 앱 소스  (0) 2013.09.16
테이블 셀 커스텀 디자인  (0) 2013.09.13
카드 짝 맞추기 게임  (0) 2013.08.29
Slider 및 TextField 및 OnOff 스위치 연습  (0) 2013.08.26
TableView 연습 코딩  (0) 2013.08.26
posted by 프띠버리 2013. 8. 29. 12:49



ViewController.h

#import <UIKit/UIKit.h>


@interface ViewController : UIViewController

{

    UIButton *prevBtn;              // 이전 버튼

    UILabel *life;                  // 생명 텍스트

}


// 현재 버튼

@property(strongnonatomicUIButton *button;

// 카드 앞면 들어갈 배열

@property(strongnonatomicNSMutableArray *frontCard;


// 액션 메소드(프로그램에서 클릭시 구동되는 시작 메소드)

- (IBAction)action:(id)sender;


@end





ViewController.m

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController

@synthesize button;             // 지금 버튼 선언

@synthesize frontCard;          // 카드 배열 선언

int count;                      // 카드 클릭 카운터 변수 선언

int chkImg;                     // 이전 클릭된 이미지를 정수로 입력받을 변수 선언

int succes;                     // 성공 횟수 변수 선언

int intvalCount;                // 오버 횟수 클릭시 처리할 변수 선언

int fail;                       // 실패 횟수 변수 선언


// 초기 화면

- (void)viewDidLoad

{

    // 초기화 메소드 불러오기

    [self initScreen];

    

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


// 초기화 메소드

-(void)initScreen

{

    // 화면 전체 클리어

    for(UIView *subview in [self.view subviews])

    {

         [subview removeFromSuperview];

    }

    

    // 버튼을 그리기 위한 for문용 변수 i, j  생성되는 버튼에 태그숫자를 붙여줄 변수 선언

    int i, j, tagNum;


    //  변수 초기화

    succes = 0;

    intvalCount = 0;

    fail = 0;

    count = 0;

    chkImg = 0;

    

    // 유동성 배열을 생성하여 초기 값을 집어 넣음

    frontCard = [[NSMutableArray allocinitWithObjects:@"1"@"1"@"2"@"2"@"3"@"3"@"4"@"4"@"5"@"5"@"6"@"6"@"7"@"7"@"8"@"8"nil];

    

    // 유동성 배열의 내용을 섞어 주는 메소드 호출

    [self shuffle];

    

    // 버튼의 태그 수를 0으로 지정

    tagNum = 0;

    

    // 제일 상단 제목 레이블로 만들기

    UILabel *label = [[UILabel allocinit];            // label이란 레이블 변수 생성

    label.frame = CGRectMake(801516020);          // 가로 80 세로 15 위치에서 가로 160, 세로 20크기의 레이블 생성

    label.text = @"카드  맞추기 게임";                     // 레이블안에 들어갈 텍스트 내용

    label.font = [UIFont systemFontOfSize:20.0];        // 레이블에 적용된 텍스트의 크기

    [self.view addSubview:label];                       // 레이블 화면에 보여주기


    // 제일 하단에 생명 하트 표시를 레이블을 이용해 텍스트로 표시

    life = [[UILabel allocinit];

    life.frame = CGRectMake(1535030040);

    life.font = [UIFont systemFontOfSize:25];

    life.text = @"생명 : ♡ ♡ ♡ ♡ ♡ ♡ ♡ ♡";

    [self.view addSubview:life];


    // 16개의 버튼 생성 하기

    for(i=0;i<4;i++)                        // 4줄로 만듬

    {

        for(j=0;j<4;j++)                    // 한줄에 4개씩 만듬

        {

            // 버튼에 이미지를 입히기 위해 커스텀 타입으로 생성

            button  = [UIButton buttonWithType:UIButtonTypeCustom];

            // 버튼의 위치를 for문을 이용하여 만듬

            button.frame = CGRectMake(15+(j*75), 50+(i*75), 6565);

            // 버튼이 생성될때 마다 태그의 값을 1 증가시킴

            tagNum += 1;

            // 버튼 태그의 값에 1 증가된 값을 집어 넣음

            button.tag = tagNum;

            // 버튼의 이미지는 backcard.jpg이고 효과는 없음

            [button setImage:[UIImage imageNamed:@"backcard.jpg"forState:UIControlStateNormal];

            // 버튼을 클릭시 sction:메소드를 실행

            [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];

            // 버튼을 화면에 보여줌

            [self.view addSubview:button];

        }

    }

    

    // 개발자요 버튼 위치 확인 부분

    for(i=0;i<16;i++)

    {

        NSLog(@"%@"frontCard[i]);

    }

}


// Mutable 배열 섞기

int randomSort(id obj1, id obj2, void*context)

{

    return (arc4random()%3 - 1);

}


- (void)shuffle

{

    [frontCard sortUsingFunction:randomSort context:nil];

}

//------------ 여기까지 배열 섞기 고정 메소드


// 버튼 클릭시 호출 되는 action: 메소드

- (IBAction)action:(id)sender

{

    // 버튼의 클릭횟수가 2보다 작을때

    if(intvalCount < 2)

    {

        // 버튼의 태그값을 알랴줌

        button = sender;

        // 버튼의 태그값에 맞춰서 체크하는 메소드 호출

        [self checkCard];

        // 1초의 대기 시간동안 클릭횟수가 2 넘어가지 않으면 intvalCtn 메소드를 호출

        [self performSelector:@selector(intvalCtn) withObject:nil afterDelay:1.0];


    }

    // 버튼의 클릭횟수가 2이상이 된다면

    else

    {

        // 경고창 호출

        UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"경고" message:@"2번만 클릭 가능합니다" delegate:self cancelButtonTitle:@"확인" otherButtonTitles:nilnil];

        [alert show];

        // 클릭횟수 변수 초기화

        intvalCount = 0;

    }

    // 클릭횟수 변수 1증가

    intvalCount += 1;

}


// 버튼의 클릭횟수가 2 넘어가지 않을때 호출되는 메소드

- (void) intvalCtn

{

    // 클릭횟수 변수 초기화

    intvalCount = 0;

}


// 클릭한 카드 2개를 비교하여 같은지 아닌지  에러 부분 체크 하는 메소드

- (void) checkCard

{

    

    // 버튼 클릭시 뒤집어 질때 태그와 배열의 값에 맞춰서 앞면 이미지 표시

    NSString *imageName = [NSString stringWithFormat:@"frontcard0%@.jpg"frontCard[button.tag-1]];

    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];

    

    // 처음 버튼 클릭시

    if(count == 0)

    {

        // 이전 이미지용 변수에 지금 클릭된 이미지의 태그값에 해당하는 이미지 번호를 정수화 하여 저장

        chkImg = [frontCard[button.tag-1intValue];

        // 이전 버튼에 현재의 버튼을 저장

        prevBtn = button;

        // 두번째 클릭을 위해 카운터 1증가

        count = count + 1;

        // 뒤집힌 카드가 다시 클릭되는것을 방지하기 위해 현재의 버튼 비활성화

        button.enabled = NO;


    }

    // 두번째 버튼 클릭시

    else if(count == 1)

    {

        // 처음 카드와 두번째 카드의 이미지 번호가 같다면

        if([frontCard[button.tag-1intValue] == chkImg)

        {

            // 성공횟수 1증가

            succes = succes + 1;

            // 카드 클릭 카운터 변수 초기화

            count = 0;

            // 이제  카드가 클릭되면 안됨으로 둘다 비활성화

            prevBtn.enabled = NO;

            button.enabled = NO;

            

            // 모든 카드가  맞았을때

            if(succes == 8)

            {

                // 게임종료 경고창 호출

                UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"VICTORY" message:@"클리어를 축하합니다." delegate:self cancelButtonTitle:@"메인으로" otherButtonTitles:@"다시하기"nil];

                [alert show];

                // 성공 횟수 초기화

                succes = 0;

            }

        }

        // 처음 카드와 두번째 카드의 이미지 번호가 다르다면

        else

        {

            // 이전 버튼을 클릭할수 있도록 활성화

            prevBtn.enabled = YES;

            // 실패 횟수 증가

            fail = fail + 1;

            

            // 뒤집힌 카드를 확인 하기 위해 0.5초후에 다시 뒷면으로 뒤집히게 

            [self performSelector:@selector(delayImg) withObject:nil afterDelay:0.5];

            

            // 실패 횟수에 따른 하트 감소 레이블 텍스트 표시

            if(fail == 1)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡ ♡ ♡ ♡ ♡";


            }

            else if(fail == 2)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡ ♡ ♡ ♡";

            }

            else if(fail == 3)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡ ♡ ♡";

            }

            else if(fail == 4)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡ ♡";

            }

            else if(fail == 5)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡";

            }

            else if(fail == 6)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡";

            }

            else if(fail == 7)

            {

                life.text = @"";

                life.text = @"생명 : ♡";

            }

            // 하트가  떨어지면

            else if(fail == 8)

            {

                life.text = @"";

                

                // 게임 실패 경고창 호출

                UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"LOSE" message:@"실패하였습니다." delegate:self cancelButtonTitle:@"메인으로" otherButtonTitles:@"다시하기"nil];

                [alert show];

                // 실패 횟수 0으로 초기화

                fail = 0;

            }

            

            //  클릭 카운터 변수 초기화

            count = 0;

        }

    }

}


// 0.5초후 뒷면 보여줄 메소드

- (void)delayImg

{

    // 이전 버튼의 이미지를 다시 뒷면이 되게 

    [prevBtn setImage:[UIImage imageNamed:@"backcard.jpg"forState:UIControlStateNormal];

    // 지금 버튼의 이미지를 다시 뒷면이 되게 

    [button setImage:[UIImage imageNamed:@"backcard.jpg"forState:UIControlStateNormal];

}


// 경고창 반응

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    // 다시하기를 클릭했을때

    if(buttonIndex == alertView.firstOtherButtonIndex)

    {

        // 게임 내용 다시 초기화

        [self initScreen];

    }

}


@end



posted by 프띠버리 2013. 8. 26. 18:38




AppDelegate.h


#import <UIKit/UIKit.h>


@class ViewController;


@interface AppDelegate : UIResponder <UIApplicationDelegate>


@property (strong, nonatomic) UIWindow *window;


@property (strong, nonatomic) ViewController *viewController;


@end



AppDelegate.m

#import "AppDelegate.h"


#import "ViewController.h"


@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];

    self.window.rootViewController = self.viewController;

    [self.window makeKeyAndVisible];

    return YES;

}



ViewController.h

#import <UIKit/UIKit.h>


@interface ViewController : UIViewController <UITextFieldDelegate>

{

    IBOutlet UILabel *label;

    IBOutlet UISlider *redSlider;

    IBOutlet UISlider *blueSlider;

    IBOutlet UISlider *greenSlider;

    IBOutlet UITextField *userInputField;

    IBOutlet UIView *colorView;

    UIActivityIndicatorView *activityIndicator;

}

- (IBAction)onColorSliderChanged:(id)sender;

- (IBAction)powerOnOff:(id)sender;


@end



ViewController.m

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    activityIndicator.center = self.view.center;

    [self.view addSubview:activityIndicator];

    [activityIndicator stopAnimating];

    

//    [redSlider setThumbImage:[UIImage imageNamed:@"red.png"] forState:UIControlStateNormal];

//    [greenSlider setThumbImage:[UIImage imageNamed:@"green.png"] forState:UIControlStateNormal];

//    [blueSlider setThumbImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];

    

    [self onColorSliderChanged:nil];

}


- (IBAction)onColorSliderChanged:(id)sender

{

    if([activityIndicator isAnimating])

    {

        [activityIndicator stopAnimating];

    }

    colorView.backgroundColor = [UIColor colorWithRed:(float)redSlider.value/255.0f green:(float)greenSlider.value/255.0f blue:(float)blueSlider.value/255.0f alpha:1.0];

    

}


- (IBAction)powerOnOff:(id)sender

{

    BOOL isOn = ((UISwitch *)sender).on;

    redSlider.enabled = isOn;

    greenSlider.enabled = isOn;

    blueSlider.enabled = isOn;

    

    if(isOn)

    {

        [activityIndicator startAnimating];

        [self performSelector:@selector(onColorSliderChanged:) withObject:nil afterDelay:1.0];

    }

    else

    {

        colorView.backgroundColor = [UIColor grayColor];

    }

}


- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    label.text = userInputField.text;

    [userInputField resignFirstResponder];

    return YES;

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




TextSliderTest.zip



슬라이더 바를 이용해서 레벨 색상 조정 및 텍스트 필드에서 입력받은 내용 레벨에 보여주기.

온오프 스위치로 활성, 비활성 선택


'Programing > IOS' 카테고리의 다른 글

테이블뷰에 웹뷰가 포함된 소스  (0) 2013.09.11
카드 짝 맞추기 게임  (0) 2013.08.29
TableView 연습 코딩  (0) 2013.08.26
기본 MP3 플레이어 기능 어플  (0) 2013.08.21
숫자야구 게임으로 앱 흉내내기  (0) 2013.08.20
posted by 프띠버리 2013. 8. 26. 17:42

AppDelegate.h

//

//  AppDelegate.h

//  TableVieww

//

//  Created by Lab10 on 13. 8. 21..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>


@class RootViewController;


@interface AppDelegate : UIResponder <UIApplicationDelegate>

{

    UINavigationController *navigationController;

}


@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) UINavigationController *navigationController;


@end



AppDelegate.m

#import "AppDelegate.h"


//#import "ViewController.h"

#import "RootViewController.h"


@implementation AppDelegate

@synthesize window;

@synthesize navigationController;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    // 애플리케이션 시작 수행될 개발자가 원하는 코드를 추가하는 부분

    UIViewController *rootController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];

    navigationController = [[UINavigationController alloc] initWithRootViewController:rootController];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    [self.window addSubview:navigationController.view];

    

    [self.window makeKeyAndVisible];

    return YES;

}



RootViewController.h



#import <UIKit/UIKit.h>

@class BooksViewController;

@interface RootViewController : UITableViewController

{

    NSArray *authorList;

    BooksViewController *booksController;

}


@property (strong, nonatomic) NSArray *authorList;

@property (strong, nonatomic) IBOutlet BooksViewController *booksController;


@end



RootViewController.m

#import "RootViewController.h"

#import "BooksViewController.h"


@interface RootViewController ()


@end


@implementation RootViewController

@synthesize authorList;

@synthesize booksController;


- (id)initWithStyle:(UITableViewStyle)style

{

    self = [super initWithStyle:style];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    self.authorList = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", nil];

    self.title = @"Month";

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

}


#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [self.authorList count];

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    

    cell.textLabel.text = [self.authorList objectAtIndex:[indexPath row]];

    

    return cell;

}


#pragma mark - Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    if(0 == indexPath.row)

    {

        self.booksController.title = @"1";

    }

    else if(1 == indexPath.row)

    {

        self.booksController.title = @"2";

    }

    else

    {

        self.booksController.title = @"3";

    }

    

    [self.navigationController pushViewController:self.booksController animated:YES];

}


@end



BooksViewController.h


#import <UIKit/UIKit.h>

@class NiceViewController;

@interface BooksViewController : UITableViewController

{

    NSArray *books;

    NiceViewController *niceController;

}

@property (strong, nonatomic) NSArray *books;

@property (strong, nonatomic) IBOutlet NiceViewController *niceController;


@end



BooksViewController.m


#import "BooksViewController.h"

#import "NiceViewController.h"


@interface BooksViewController ()


@end


@implementation BooksViewController

@synthesize books;

@synthesize niceController;


- (id)initWithStyle:(UITableViewStyle)style

{

    self = [super initWithStyle:style];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];


}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

}


#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [books count];

}


- (void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    if([self.title isEqualToString:@"1"])

    {

        books = [[NSArray alloc] initWithObjects:@"1 1", @"1 2", @"1 3", @"1 4", @"1 5", @"1 6", nil];

    }

    else if([self.title isEqualToString:@"2"])

    {

        books = [[NSArray alloc] initWithObjects:@"2 1", @"2 2", @"2 3", @"2 4", @"2 5", nil];

    }

    else

    {

        books = [[NSArray alloc] initWithObjects:@"3 1", @"3 2", @"3 3", @"3 4", @"3 5", @"3 6", nil];

    }


    [self.tableView reloadData];

    

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    

    cell.textLabel.text = [books objectAtIndex:[indexPath row]];

    

    return cell;

}



#pragma mark - Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    if([self.title isEqualToString:@"1"])

    {

        if(0 == indexPath.row)

        {

            self.niceController.title = @"1 1";

        }

        else if(1 == indexPath.row)

        {

            self.niceController.title = @"1 2";

        }

        else if(2 == indexPath.row)

        {

            self.niceController.title = @"1 3";

        }

        else if(3 == indexPath.row)

        {

            self.niceController.title = @"1 4";

        }

        else if(4 == indexPath.row)

        {

            self.niceController.title = @"1 5";

        }

        else

        {

            self.niceController.title = @"1 6";

        }

    }

    else if([self.title isEqualToString:@"2"])

    {

        if(0 == indexPath.row)

        {

            self.niceController.title = @"2 1";

        }

        else if(1 == indexPath.row)

        {

            self.niceController.title = @"2 2";

        }

        else if(2 == indexPath.row)

        {

            self.niceController.title = @"2 3";

        }

        else if(3 == indexPath.row)

        {

            self.niceController.title = @"2 4";

        }

        else

        {

            self.niceController.title = @"2 5";

        }

    }

    else

    {

        if(0 == indexPath.row)

        {

            self.niceController.title = @"3 1";

        }

        else if(1 == indexPath.row)

        {

            self.niceController.title = @"3 2";

        }

        else if(2 == indexPath.row)

        {

            self.niceController.title = @"3 3";

        }

        else if(3 == indexPath.row)

        {

            self.niceController.title = @"3 4";

        }

        else if(4 == indexPath.row)

        {

            self.niceController.title = @"3 5";

        }

        else

        {

            self.niceController.title = @"3 6";

        }

    }


    [self.navigationController pushViewController:self.niceController animated:YES];

}

@end



NiceViewController.h

#import <UIKit/UIKit.h>


@interface NiceViewController : UITableViewController

{

    NSArray *nice;

}


@property (strong, nonatomic) NSArray *nice;


@end



NiceViewController.m

#import "NiceViewController.h"


@interface NiceViewController ()


@end


@implementation NiceViewController

@synthesize nice;


- (id)initWithStyle:(UITableViewStyle)style

{

    self = [super initWithStyle:style];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

}


#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [nice count];

}


- (void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    if([self.title isEqualToString:@"1 1"])

    {

         nice = [[NSArray alloc] initWithObjects:@"1kg", @"1cm", @"1", @"", nil];

    }

    else if([self.title isEqualToString:@"1 2"])

    {

        nice = [[NSArray alloc] initWithObjects:@"2kg", @"2cm", @"2", @"", nil];

    }

    else if([self.title isEqualToString:@"1 3"])

    {

        nice = [[NSArray alloc] initWithObjects:@"3kg", @"3cm", @"3", @"", nil];

    }

    else if([self.title isEqualToString:@"1 4"])

    {

        nice = [[NSArray alloc] initWithObjects:@"4kg", @"4cm", @"4", @"", nil];

    }

    else if([self.title isEqualToString:@"1 5"])

    {

        nice = [[NSArray alloc] initWithObjects:@"5kg", @"5cm", @"5", @"", nil];

    }

    else if([self.title isEqualToString:@"1 6"])

    {

        nice = [[NSArray alloc] initWithObjects:@"6kg", @"6cm", @"6", @"", nil];

    }

    else if([self.title isEqualToString:@"2 1"])

    {

        nice = [[NSArray alloc] initWithObjects:@"7kg", @"7cm", @"7", @"", nil];

    }

    else if([self.title isEqualToString:@"2 2"])

    {

        nice = [[NSArray alloc] initWithObjects:@"8kg", @"8cm", @"8", @"", nil];

    }

    else if([self.title isEqualToString:@"2 3"])

    {

        nice = [[NSArray alloc] initWithObjects:@"9kg", @"9cm", @"9", @"", nil];

    }

    else if([self.title isEqualToString:@"2 4"])

    {

        nice = [[NSArray alloc] initWithObjects:@"10kg", @"10cm", @"10", @"", nil];

    }

    else if([self.title isEqualToString:@"2 5"])

    {

        nice = [[NSArray alloc] initWithObjects:@"11kg", @"11cm", @"10", @"", nil];

    }

    else if([self.title isEqualToString:@"3 1"])

    {

        nice = [[NSArray alloc] initWithObjects:@"12kg", @"12cm", @"11", @"", nil];

    }

    else if([self.title isEqualToString:@"3 2"])

    {

        nice = [[NSArray alloc] initWithObjects:@"13kg", @"13cm", @"12", @"", nil];

    }

    else if([self.title isEqualToString:@"3 3"])

    {

        nice = [[NSArray alloc] initWithObjects:@"14kg", @"14cm", @"13", @"", nil];

    }

    else if([self.title isEqualToString:@"3 4"])

    {

        nice = [[NSArray alloc] initWithObjects:@"15kg", @"15cm", @"14", @"", nil];

    }

    else if([self.title isEqualToString:@"3 5"])

    {

        nice = [[NSArray alloc] initWithObjects:@"16kg", @"16cm", @"15", @"", nil];

    }

    else

    {

        nice = [[NSArray alloc] initWithObjects:@"17kg", @"17cm", @"16", @"", nil];

    }

    

    [self.tableView reloadData];

    

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    

    // Configure the cell...

    cell.textLabel.text = [nice objectAtIndex:[indexPath row]];

    

    return cell;

}



#pragma mark - Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    

}

@end



테이블뷰를 이용한 이동 관련 소스

posted by 프띠버리 2013. 8. 21. 17:40





MasterViewController.h


//

//  MasterViewController.h

//  MP3Player

//

//  Created by Lab10 on 13. 8. 6..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>


// 헤더 추가

//#import "AVFoundation/AVAudioPlayer.h"

//#define AUDIO_PLAYER_EXAM   // AVAudioPlayer 기능 테스트


@class DetailViewController;


@interface MasterViewController : UITableViewController

{

    // 오디오 재생 클래스

    //AVAudioPlayer *audioPlayer;

    

    // mp3 리스트

    NSArray *dirContents;

    

}


@property (strong, nonatomic) DetailViewController *detailViewController;


@end



MasterViewController.m


//

//  MasterViewController.m

//  MP3Player

//

//  Created by Lab10 on 13. 8. 6..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import "MasterViewController.h"


#import "DetailViewController.h"


// 헤더 추가

#import "MP3ViewController.h"



@interface MasterViewController () {

    NSMutableArray *_objects;

}


@end


@implementation MasterViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        //self.title = NSLocalizedString(@"Master", @"Master");

        self.title = @"MP3 Player";

        

    }

    return self;

}

- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    

#ifdef AUDIO_PLAYER_EXAM

    // 번들 mp3파일 경로 생성

    NSString *mp3FilePath=[[NSBundle mainBundle] pathForResource:@"tellmetellme" ofType:@"mp3"];

    

    // NSURL 형식으로 변환

    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:mp3FilePath];

    

    // 오디오 플레이어 생성

    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];

    

    // 사운드 재생 준비 확인

    [audioPlayer prepareToPlay];

    

#endif

    

    // 상태 스타일 변경

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];

    

    // 네비게이션 스타일 변경

    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;

    

    // 도큐먼트 디렉터리에서 mp3 파일을 획득하여 리스트 생성

    NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *docDir = [docPath objectAtIndex:0];

    NSArray *extensions = [NSArray arrayWithObjects:@"mp3", @"MP3", nil];

    NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docDir error:nil];

    dirContents = [contents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"pathExtension IN %@", extensions]];

    

//    self.navigationItem.leftBarButtonItem = self.editButtonItem;


//    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];

//    self.navigationItem.rightBarButtonItem = addButton;

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (void)insertNewObject:(id)sender

{

    if (!_objects) {

        _objects = [[NSMutableArray alloc] init];

    }

    [_objects insertObject:[NSDate date] atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

}


//#pragma mark - Table View


//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

//{

//    return 1;

//    return [dirContents count];

//}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    //return _objects.count;

    return [dirContents count];

}


// 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:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }



   // NSDate *object = _objects[indexPath.row];

   // cell.textLabel.text = [object description];

    

#ifdef AUDIO_PLAYER_EXAM

    if(audioPlayer.isPlaying)

    {

        // 재생 중이면 [일시정지] 표시

        cell.textLabel.text = @"PAUSE";

    }

    else

    {

        // 재생 중이 아니면 [재생] 표시

        cell.textLabel.text = @"PLAY";

    }

#endif

    

    cell.textLabel.text = [dirContents objectAtIndex:indexPath.row];

    

    return cell;

}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{

    // Return NO if you do not want the specified item to be editable.

    return YES;

}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        [_objects removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

    } else if (editingStyle == UITableViewCellEditingStyleInsert) {

        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.

    }

}


/*

// Override to support rearranging the table view.

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath

{

}

*/


/*

// Override to support conditional rearranging of the table view.

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

{

    // Return NO if you do not want the item to be re-orderable.

    return YES;

}

*/


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

#ifdef AUDIO_PLAYER_EXAM

    if(audioPlayer.isPlaying)

    {

        // 재생 중이면 일시정지

        [audioPlayer pause];

    }

    else

    {

        // 재생 중이 아니면 재생 시작

        [audioPlayer play];

    }

    // 테이블 갱신

    [self.tableView reloadData];

#endif

    // MP3ViewController 생성 삽입

    MP3ViewController *subViewController = [[MP3ViewController alloc] initWithNibName:@"MP3ViewController" bundle:nil];

    [subViewController setFileList:dirContents fileIndex:indexPath.row];

    [self.navigationController pushViewController:subViewController animated:YES];

    

}


@end


DetailViewController.h


//

//  DetailViewController.h

//  MP3Player

//

//  Created by Lab10 on 13. 8. 6..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface DetailViewController : UIViewController


@property (strong, nonatomic) id detailItem;


@property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;

@end



DetailViewController.m

//

//  DetailViewController.m

//  MP3Player

//

//  Created by Lab10 on 13. 8. 6..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import "DetailViewController.h"


@interface DetailViewController ()

- (void)configureView;

@end


@implementation DetailViewController


#pragma mark - Managing the detail item


- (void)setDetailItem:(id)newDetailItem

{

    if (_detailItem != newDetailItem) {

        _detailItem = newDetailItem;

        

        // Update the view.

        [self configureView];

    }

}


- (void)configureView

{

    // Update the user interface for the detail item.


    if (self.detailItem) {

        self.detailDescriptionLabel.text = [self.detailItem description];

    }

}


- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    [self configureView];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        self.title = NSLocalizedString(@"Detail", @"Detail");

    }

    return self;

}

@end



MP3ViewController.h


//

//  MP3ViewController.h

//  MP3Player

//

//  Created by Lab10 on 13. 8. 6..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>


// 헤더 추가

#import "AVFoundation/AVAudioPlayer.h"

#import "MediaPlayer/MPVolumeView.h"


// 메타 데이터 관련 헤더

#import "AVFoundation/AVAsset.h"

#import "AVFoundation/AVMetadataItem.h"


// 재생 상태 열거

typedef enum PLAY_STATE{

    NOT_READY = 0// 준비되지 않음

    PLAYING,        // 재생

    PAUSED,         // 일시정지

    STOPPED,        // 정지

}_PLAY_STATE;



@interface MP3ViewController : UIViewController

{

    // 오디오 재생 클래스

    AVAudioPlayer *audioPlayer;

    

    // 파일 리스트

    NSArray *fileList;

    

    // 파일 인덱스

    NSInteger fileIndex;

    

    // 타임라인 슬라이더

    UISlider *timeSlider;

    

    // 볼륨 컨트롤

    MPVolumeView *volumeView;

    

    // 현재 시간

    UILabel *curTime;

    

    // 재생 시간

    UILabel *totTime;

    

    // 재생 버튼

    UIButton *btnPlay;

    

    // 파일 이름

    NSString *fileName;

    

    // 컨트롤 배경

    UIImageView *ctrlBg;

    

    // 슬라이더 배경

    UIImageView *progBg;

    

    // 이전 버튼

    UIButton *btnPrev;

    

    // 일시정지 버튼

    UIButton *btnPause;

    

    // 다음 버튼

    UIButton *btnNext;

    

    // 재킷 이미지

    UIImageView *artworkView;

    

    // 재생 상태

    int playState;

    

    // 오버레이 상태

    BOOL bOverlay;

    

    // 드래깅 상태

    BOOL bDragging;

    

    // 타이머

    NSTimer *tsTimer;

}


// 파일 리스트 설정

- (void) setFileList:(NSArray *)list fileIndex:(NSInteger) index;


@end



MP3ViewController.m


//

//  MP3ViewController.m

//  MP3Player

//

//  Created by Lab10 on 13. 8. 6..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import "MP3ViewController.h"


@interface MP3ViewController ()


@end


@implementation MP3ViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    

    // 타이틀을 파일명으로 변경

    self.title = [fileList objectAtIndex:fileIndex];

    

    

    // 파일 URL 생성

    NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *docDirectory = [sysPaths objectAtIndex:0];

    NSString *filePath = [NSString stringWithFormat:@"%@/%@", docDirectory, [fileList objectAtIndex:fileIndex]];

    

    // 재킷 이미지 출력

    [self artworksForFileAtPath:filePath];

    

    // 플레이어 컨트롤 초기화

    [self initPlayerControls];

    

    // 오디오 플레이어 생성

    NSURL *url = [NSURL fileURLWithPath:filePath];

    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    audioPlayer.delegate = (id)self;

    

    if(audioPlayer == nil)

    {

        return;

    }

    else

    {

        if([audioPlayer prepareToPlay])

        {

            // 탐색 슬라이더 설정

            [timeSlider setMaximumValue:[audioPlayer duration]];

            

            // 현재 시간 업데이트 타이머 시작

            tsTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimeStamp) userInfo:nil repeats:YES];

            

            // 재생 시작

            [audioPlayer play];

            

        }

    }

}



// 뷰가 사라질 처리를 위해서 추가

- (void) viewWillDisappear:(BOOL)animated

{

    // 재생 중인 경우 정지

    if(audioPlayer.isPlaying)

    {

        [audioPlayer stop];

    }

    

    [super viewWillDisappear:animated];

    

}


// 재생 종료 델리게이트 매서드

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

{

    // 다음 곡을 재생

    [self onBtnNext];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


// 오디오 파일 리스트 인덱스 설정

- (void) setFileList:(NSArray *)list fileIndex:(NSInteger)index

{

    // 파일 리스트 저장

    fileList = list;

    

    // 현재 파일 인덱스 저장

    fileIndex = index;

    

}


// MP3 파일에서 Artwork 이미지 추출

- (void)artworksForFileAtPath:(NSString *)path

{

    if (!artworkView)

    {

        // 재킷 이미지 출력을 위한 이미지 뷰를 생성

        artworkView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];

        artworkView.userInteractionEnabled = YES;

        [self.view addSubview:artworkView];

        

        // 제스처를 등록

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(overlaySwitch)];

        [tap setNumberOfTapsRequired:1];

        [artworkView addGestureRecognizer:tap];

        

    }

    

    // 파일의 메타데이터를 획득

    AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:path] options:nil];

    NSArray *metadata = [asset commonMetadata];

    

    // artwork 데이터를 artworkView 적용

    for (AVMetadataItem* item in metadata)

    {

        if([[item commonKey] isEqualToString:@"artwork"])

        {

            UIImage *artworkImage = nil;

            if([[item value] isKindOfClass:[NSDictionary class]])

            {

                NSDictionary *imageDic = (NSDictionary *) [item value];

                

                if([imageDic objectForKey:@"data"] != nil)

                {

                    NSData *imageData = [imageDic objectForKey:@"data"];

                    artworkImage = [UIImage imageWithData:imageData];

                    artworkView.image = artworkImage;

                }

            }

        }

    }

}



// 오디오 파일 다시 재생

- (void) restartPlayer

{

    // 타이틀 변경

    self.title = [fileList objectAtIndex:fileIndex];

    

    // 파일 URL 생성

    

    NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *docDirectory = [sysPaths objectAtIndex:0];

    NSString *filePath = [NSString stringWithFormat:@"%@/%@", docDirectory, [fileList objectAtIndex:fileIndex]];

    

    NSURL *url = [NSURL fileURLWithPath:filePath];

    

    

    // 오디오 플레이어 생성 적용

    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    player.delegate = (id)self;

    audioPlayer = player;

    

    

    // 컨트롤 세팅 재생 시작

    if([audioPlayer prepareToPlay])

    {

        // 탐색 범위 설정

        [timeSlider setMaximumValue:[audioPlayer duration]];

        

        // 타이머 리셋

        [tsTimer invalidate];

        tsTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimeStamp) userInfo:nil repeats:YES];

        

        // 재킷 이미지 변경

        [self artworksForFileAtPath:filePath];

        

        // 재생 시작

        [audioPlayer play];

        

    }

}


// 이전 버튼 이벤트

- (void) onBtnPrev

{

    if(fileIndex == 0)

    {

        fileIndex = [fileList count]-1;

    }

    else

    {

        fileIndex--;

    }

    btnPlay.hidden = YES;

    btnPause.hidden = NO;

    [self restartPlayer];

}



// 다음 버튼 이벤트

- (void) onBtnNext

{

    if([fileList count] <= fileIndex+1)

    {

        fileIndex = 0;

    }

    else

    {

        fileIndex++;

    }

    btnPlay.hidden = YES;

    btnPause.hidden = NO;

    [self restartPlayer];

}



// 재생 버튼 이벤트

- (void) onBtnPlay

{

    // 상태 변경 재생 시작

    playState = PLAYING;

    btnPlay.hidden = YES;

    btnPause.hidden = NO;

    [audioPlayer play];

}



// 일시정지 버튼 이벤트

- (void) onBtnPause

{

    // 상태 변경 일시정지

    playState = PAUSED;

    btnPlay.hidden = NO;

    btnPause.hidden = YES;

    [audioPlayer pause];

}



// 오버레이 보이기/숨기기

- (void) showOverlay:(BOOL) show

{

    progBg.hidden = timeSlider.hidden = curTime.hidden = totTime.hidden = !show;

}


// 오버레이 상태 변경

- (void) overlaySwitch

{

    // 오버레이 플래그를 변경

    bOverlay = !bOverlay;

    [self showOverlay:bOverlay];

}


// 재생시간 업데이트

- (void) updateTimeStamp

{

    // 플레이어가 생성되지 않은 경우 타이머 종료

    if(audioPlayer == nil)

    {

        [tsTimer invalidate];

        tsTimer = nil;

        return;

    }

    

    // 드레깅 중에는 취소

    if(bDragging) return;

    

    // 현재 시간, 남은 시간 계산

    int cur = (int)[audioPlayer currentTime];

    int ext = (int)[audioPlayer duration]-cur;

    

    // 슬라이더 위치 변경

    [timeSlider setValue:[audioPlayer currentTime]];

    

    // 시간 업데이트

    [curTime setText:[NSString stringWithFormat:@"%02d:%02d", cur/60, cur%60]];

    [totTime setText:[NSString stringWithFormat:@"-%02d:%02d", ext/60, ext%60]];

    

}



// 타임라인 드래그 처리

- (void) slideDragging

{

    

    // 현재 시간, 남은 시간 계산

    int cur = (int)timeSlider.value;

    int ext = (int)timeSlider.maximumValue-cur;

    

    // 시간 업데이트

    if(audioPlayer != nil)

    {

        [curTime setText:[NSString stringWithFormat:@"%02d:%02d", cur/60, cur%60]];

        [totTime setText:[NSString stringWithFormat:@"-%02d:%02d", ext/60, ext%60]];

        

    }

}



// 슬라이드 선택

- (void) slideSelected

{

    // 플래그 변경

    bDragging = YES;

}


// 슬라이드 해제

- (void) slideRelease

{

    // 플래그 변경

    bDragging = NO;

    

    // 재생 위치를 변경

    [audioPlayer setCurrentTime:timeSlider.value];

    

}



// 플레이어 컨트롤 초기화

- (void) initPlayerControls

{

    

    // 아래쪽 생성

    ctrlBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bottom_bar.png"]];

    ctrlBg.frame = CGRectMake(0, 320, 320, 96);

    [self.view addSubview:ctrlBg];

    

    // 탐색 슬라이더 배경

    progBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"progress_bg.png"]];

    progBg.frame = CGRectMake(0, 0, 320, 44);

    progBg.alpha = 0.9f;

    [self.view addSubview:progBg];

    

    // 탐색 슬라이더

    timeSlider = [[UISlider alloc] initWithFrame:CGRectMake(50, 12, 220, 22)];

    [self.view addSubview:timeSlider];

    [timeSlider addTarget:self action:@selector(slideDragging) forControlEvents:UIControlEventTouchDragInside];

    [timeSlider addTarget:self action:@selector(slideSelected) forControlEvents:UIControlEventTouchDown];

    [timeSlider addTarget:self action:@selector(slideRelease) forControlEvents:UIControlEventTouchUpInside];

    [timeSlider addTarget:self action:@selector(slideRelease) forControlEvents:UIControlEventTouchUpOutside];

    

    // 현재 시간, 남은 시간 출력 레이블

    curTime = [[UILabel alloc] initWithFrame:CGRectMake(10, 12, 35, 22)];

    curTime.text = @"00:00";

    totTime = [[UILabel alloc] initWithFrame:CGRectMake(275, 12, 40, 22)];

    totTime.text = @"-00:00";

    curTime.backgroundColor = totTime.backgroundColor = [UIColor clearColor];

    curTime.textColor = totTime.textColor = [UIColor whiteColor];

    curTime.font = totTime.font = [UIFont boldSystemFontOfSize:12];

    // curTime.textAlignment = UITextAlignmentRight;

    [self.view addSubview:curTime];

    [self.view addSubview:totTime];

    

    // 이전 버튼

    btnPrev = [[UIButton alloc] init];

    btnPrev.frame = CGRectMake(64, 325, 44, 44);

    [btnPrev setImage:[UIImage imageNamed:@"button_prev.png"] forState:UIControlStateNormal];

    [btnPrev addTarget:self action:@selector(onBtnPrev) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btnPrev];

    

    // 재생시작 버튼

    btnPlay = [[UIButton alloc] init];

    btnPlay.frame = CGRectMake(138, 325, 44, 44);

    [btnPlay setImage:[UIImage imageNamed:@"button_play.png"] forState:UIControlStateNormal];

    [btnPlay addTarget:self action:@selector(onBtnPlay) forControlEvents:UIControlEventTouchUpInside];

    btnPlay.hidden = YES;

    [self.view addSubview:btnPlay];

    

    // 일시정지 버튼

    btnPause = [[UIButton alloc] init];

    btnPause.frame = CGRectMake(138, 325, 44, 44);

    [btnPause setImage:[UIImage imageNamed:@"button_pause.png"] forState:UIControlStateNormal];

    [btnPause addTarget:self action:@selector(onBtnPause) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btnPause];


    // 다음 버튼

    btnNext = [[UIButton alloc] init];

    btnNext.frame = CGRectMake(212, 325, 44, 44);

    [btnNext setImage:[UIImage imageNamed:@"button_next.png"] forState:UIControlStateNormal];

    [btnNext addTarget:self action:@selector(onBtnNext) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btnNext];

    

    // 볼륨 조절 컨트롤

    volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(30, 370, 260, 46)];

    [volumeView sizeToFit];

    [self.view addSubview:volumeView];

    

    // 오버레이 컨트롤 감춤

    [self showOverlay:bOverlay];

    

}

@end

posted by 프띠버리 2013. 8. 20. 17:30






NumberBaseball2.zip



소스 부분

ViewController.h

//

//  ViewController.h

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface ViewController : UIViewController


- (IBAction)playball;

- (IBAction)help;


@end


ViewController.m

//

//  ViewController.m

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import "ViewController.h"

// 게임과 도움 헤더파일 포함

#import "playball.h"

#import "help.h"


@interface ViewController ()


@end


@implementation ViewController


// 게임 시작 화면으로 이동

- (IBAction)playball

{

    playball *view = [[playball alloc] initWithNibName:@"playball" bundle:nil];

    view.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

    [self presentViewController:view animated:YES completion:nil];

}


// 도움말 화면으로 이동

- (IBAction)help

{

    help *view = [[help alloc] initWithNibName:@"help" bundle:nil];

    view.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

    [self presentViewController:view animated:YES completion:nil];

}


- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


help.h

//

//  help.h

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface help : UIViewController


- (IBAction)mainmenu;


@end


help.m

//

//  help.m

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import "help.h"


@interface help ()


@end


@implementation help


// 메인화면으로 돌아가기

- (IBAction)mainmenu

{

    [self dismissViewControllerAnimated:YES completion:nil];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


playball.h

//

//  playball.h

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import <UIKit/UIKit.h>

// 사운드를 위해  AVAFound 포함

#import <AVFoundation/AVFoundation.h>


@interface playball : UIViewController<AVAudioPlayerDelegate>

{

    AVAudioPlayer *theAudio;

}


@property (strong, nonatomic) IBOutlet UITextField *InputNum1;

@property (strong, nonatomic) IBOutlet UITextField *InputNum2;

@property (strong, nonatomic) IBOutlet UITextField *InputNum3;

@property (strong, nonatomic) IBOutlet UITextView *viewText;

- (IBAction)btnHit:(id)sender;


- (IBAction)mainmenu;


@end


playball.m

//

//  playball.m

//  NumberBaseball2

//

//  Created by Lab10 on 13. 8. 19..

//  Copyright (c) 2013 Lab10. All rights reserved.

//


#import "playball.h"


@interface playball ()


@end


@implementation playball

@synthesize InputNum1;              // 텍스트필드 1 정의

@synthesize InputNum2;              // 텍스트필드 2 정의

@synthesize InputNum3;              // 텍스트필드 3 정의

@synthesize viewText;               // 텍스트뷰 정의

NSString *result;                   // 결과를 보여줄 문자열 전역으로 정의

NSNumber *nnum1;                    // 랜덤 생성할 1 숫자

NSNumber *nnum2;                    // 랜덤 생성할 2 숫자

NSNumber *nnum3;                    // 랜덤 생성할 3 숫자

int count = 0;                      // 카운트 표시


- (IBAction)btnHit:(id)sender {

    // 스트라이크와 볼을 구하기 위한 변수 선언

    int ball = 0, strick = 0;

    

    // 텍스트 필드로 입력 받은 넘기기

    NSNumber *num1 = [[NSNumber alloc] initWithInt:[InputNum1.text intValue]];

    NSNumber *num2 = [[NSNumber alloc] initWithInt:[InputNum2.text intValue]];

    NSNumber *num3 = [[NSNumber alloc] initWithInt:[InputNum3.text intValue]];

    

    // 배열에 텍스트 필드로 받은 넣기

    NSArray *intNum = [NSArray arrayWithObjects: num1, num2, num3, nil];

    

    // 랜덤 숫자 배열에 넣기

    NSArray *resNum = [NSArray arrayWithObjects: nnum1, nnum2, nnum3, nil];

    

    // 텍스트 필드가 공백일때

    if([InputNum1.text isEqualToString:@""] || [InputNum2.text isEqualToString:@""] || [InputNum3.text isEqualToString:@""])

    {

        viewText.text = @"공백은 입력할수 없습니다.";

        NSLog(@"빈칸이랑께");

    }

    // 텍스트 필드에 문자가 입력되었을때

//    else if(![InputNum1.text intValue] || ![InputNum2.text intValue] || ![InputNum3.text intValue])

//    {

//        viewText.text = @"문자는 입력할수 없습니다.";

//        NSLog(@"문자시져");

//    }

    // 텍스트 필드의 숫자가 두자리 이상일때

    else if([InputNum1.text intValue] > 9 || [InputNum2.text intValue] > 9 || [InputNum3.text intValue] > 9)

    {

        viewText.text = @"숫자는 한자리수만 가능합니다.";

        NSLog(@"숫자많앙");

    }

    // 텍스트 필드의 숫자가 중복되었을때

    else if([InputNum1.text intValue] == [InputNum2.text intValue] || [InputNum1.text intValue] == [InputNum3.text intValue] || [InputNum2.text intValue] == [InputNum3.text intValue])

    {

        viewText.text = @"중복된 숫자는 사용할수 없습니다.";

        NSLog(@"중복이양");

    }

    // 모든 예외체크를 통과 했다면

    else

    {

        count = count + 1;

        // 스트라이크와 볼을 구하는 부분

        for(int i=0;i<3;i++)

        {

            // 입력받은 수와 지정된 임의의 수를 비교하여 스트라이크 구하기

            if([intNum objectAtIndex:i] == [resNum objectAtIndex:i])

            {

                strick = strick + 1;                    // 자리와 숫자가 일치하면 스트라이크+1

                NSLog(@"%d 스트라이크", strick);

            }

            

            // 입력받은 수와 지정된 임의의 수를 비교하여 구하기

            if([intNum objectAtIndex:i] != [resNum objectAtIndex:i])

            {

                // 첫번째 숫자 부터 같은지 비교 시작

                for(int j=0;j<3;j++)

                {

                    // 만약 자리가 다르고 같은수가 있다면

                    if([intNum objectAtIndex:i] == [resNum objectAtIndex:j])

                    {

                        ball = ball + 1;                // +1

                        NSLog(@"%d ", ball);

                    }

                }

            }

        }

        

        // 텍스트 필드로 입력받은 숫자와 스트라이크 표시

        NSString *msg = [NSString stringWithFormat:@"%2d : %@ %@ %@ () %d %d 스트라이크 입니다.\n", count, [intNum objectAtIndex:0], [intNum objectAtIndex:1], [intNum objectAtIndex:2], ball, strick];

        

        // 앞의 진행상황을 계속해서 보여줌

        result = [NSString stringWithFormat:@"%@%@", result, msg];

        

        // 뷰텍스트에 표시

        viewText.text = result;

        

    }

    // 3스트라이크가 되었을때 승리창 띄우기

    if(strick == 3)

    {

        // 승리 사운드

        NSString *path = [[NSBundle mainBundle] pathForResource:@"woo" ofType:@"wav"];

        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

        theAudio.delegate = self;

        [theAudio play];

        

        // 경고창

        NSString *msg = [NSString stringWithFormat:@"축하합니다! 당신의 승리입니다."];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You WIN!!" message:msg delegate:self cancelButtonTitle:@"메인으로" otherButtonTitles:@"다시하기", nil];

        alert.tag = 11;

        [alert show];

    }

    // 10 동안안에 맞추면 패배창 띄우기

    if(strick !=3 && count == 10)

    {

        // 패배 사운드

        NSString *path2 = [[NSBundle mainBundle] pathForResource:@"boo" ofType:@"wav"];

        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:NULL];

        theAudio.delegate = self;

        [theAudio play];

        

        // 경고창

        NSString *msg = [NSString stringWithFormat:@"당신은 패배하였습니다."];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You LOSE!!" message:msg delegate:self cancelButtonTitle:@"메인으로" otherButtonTitles:@"다시하기", nil];

        alert.tag = 12;

        [alert show];

    }

    

    // 텍스트 필드 초기화

    InputNum1.text = @"";

    InputNum2.text = @"";

    InputNum3.text = @"";

    

    // 텍스트 필드 리턴시 자판 내려가기

    [InputNum1 resignFirstResponder];

    [InputNum2 resignFirstResponder];

    [InputNum3 resignFirstResponder];

}


// UIALertView설정

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if(buttonIndex == alertView.firstOtherButtonIndex)

    {

        [self initPlayball];

    }else

    {

        [self mainmenu];

    }

}


// 메인 화면으로 돌아가기

- (IBAction)mainmenu

{

    [self dismissViewControllerAnimated:YES completion:nil];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

 

    [self initPlayball];

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


// 게임 초기화

- (void)initPlayball

{

    // 텍스트 필드에서 자판 번호모양으로 표시

    InputNum1.keyboardType=UIKeyboardTypeNumberPad;

    InputNum2.keyboardType=UIKeyboardTypeNumberPad;

    InputNum3.keyboardType=UIKeyboardTypeNumberPad;

    

    // 텍스트 필드 초기화

    [InputNum1 setText:@""];

    [InputNum2 setText:@""];

    [InputNum3 setText:@""];

    

    // nnum 초기화 시켜주기

    nnum1 = 0;

    nnum2 = 0;

    nnum3 = 0;

    count = 0;

    

    viewText.text = @"";

    

    // 랜덤 숫자 3 구하기

    while(nnum1 == nnum2 || nnum2 == nnum3 || nnum3 == nnum1)

    {

        nnum1 = [[NSNumber alloc] initWithInt:arc4random()%10];

        nnum2 = [[NSNumber alloc] initWithInt:arc4random()%10];

        nnum3 = [[NSNumber alloc] initWithInt:arc4random()%10];

    }

    

    NSLog(@"%@ %@ %@", nnum1, nnum2, nnum3);   // 개발자 CMD화면에 랜덤 찍어보기

    

    // 텍스트 결과창 초기화

    result = @"";


}

@end



'Programing > IOS' 카테고리의 다른 글

테이블뷰에 웹뷰가 포함된 소스  (0) 2013.09.11
카드 짝 맞추기 게임  (0) 2013.08.29
Slider 및 TextField 및 OnOff 스위치 연습  (0) 2013.08.26
TableView 연습 코딩  (0) 2013.08.26
기본 MP3 플레이어 기능 어플  (0) 2013.08.21