[obj-c] UITableView

iPhone 2012. 11. 20. 11:53

UITableView



contentOffset : content의 처음부터 현재 위치한 곳까지의 거리

contentSize : 테이블뷰가 가진 컨텐츠의 거리







** (CGFloat)tableView:heightForRowAtIndexPath는 (UITableViewCell *)cellForRowAtIndexPath보다 빨리 불린다.




셀을 선택했을 때, Hightlight color 없애기


cell.selectionStyle = UITableViewCellSelectionStyleNone;






indexPath로 현재셀 얻기



 [self tableView:tableView cellForRowAtIndexPath:indexPath];






셀안에 이미지 넣기 



>>> tableView:cellForRowAtIndexPath 안에서


NSString *imagePath = @"image.jpg";     

cell.image = [UIImage imageNamed:imagePath]; 






구분선 없애기



tableView.separatorStyle = UITableViewCellSeparatorStyleNone;





셀이 각각 다른 높이를 가질 때


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath









스크롤 한후, 테이블 상단과 셀의 위치 맞춰주기


- (void)scrollViewDidEndDecelerating:(UITableView *)tableView {

    int tomove = ((int)tableView.contentOffset.y%(int)tableView.rowHeight);

    

    if(tomove < tableView.rowHeight/2){

        [tableView setContentOffset:CGPointMake(0, tableView.contentOffset.y-tomove) animated:YES];

    }else{

        [tableView setContentOffset:CGPointMake(0, tableView.contentOffset.y+(tableView.rowHeight-tomove)) animated:YES];

    }

    

}


- (void)scrollViewDidEndDragging:(UITableView *)scrollView willDecelerate:(BOOL)decelerate {

    if(decelerate) return;

    [self scrollViewDidEndDecelerating:scrollView];

}




드래그로 페이징







바운드 영역을 바꿈

tableView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f); //첫번째 값을 바꾸면 y축의 바운드영역이 바뀜




Posted by tenn
,

[objc] UIImage

iPhone 2012. 11. 20. 11:21


리소스의 이미지 가져오기 


[UIImage imageNamed:@"image_resource_name"]






UImage copy



        UIImage *source = [UIImage imageNamed:@"src.png"];

        

        CGSize size = [source size];

        

        UIGraphicsBeginImageContext(size);

        CGRect rect = CGRectMake(0, 0, size.width, size.height);

        [source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];

        

        CGContextRef context = UIGraphicsGetCurrentContext();


        CGContextStrokeRect(context, rect);

        UIImage *testImg =  UIGraphicsGetImageFromCurrentImageContext();   //  <- 결과 이미지

        UIGraphicsEndImageContext();

        





URL에서 이미지 읽어오기



NSURL *imageURL = [NSURL URLWithString:@"http://example.com/demo.jpg"];


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];


    dispatch_async(dispatch_get_main_queue(), ^{

        // Update the UI

        self.imageView.image = [UIImage imageWithData:imageData];

    });

});


http://stackoverflow.com/questions/7694215/create-a-uiimage-with-a-url-in-ios











Posted by tenn
,

[objc] xib 참조하기

iPhone 2012. 11. 19. 18:42



NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"xibfilename" owner:self options:nil];

UIView *view = (UIView *)[nib objectAtIndex:0];

Posted by tenn
,



 

 NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"tragetView" owner:self options:nil];

UIView *nibView = [nibObjects objectAtIndex:0];


UIViewController *viewController = [[UIViewController alloc] init];

                viewController.view = nibView;

                viewController.view.frame = CGRectMake(0, 23, nibView.frame.size.width,nibView.frame.size.height);

Posted by tenn
,

[objc] 뷰간의 이동

iPhone 2012. 11. 13. 19:06



스토리보드에서 push로 지정했으나, 상황에 따라 다른 뷰로 이동하고 싶다.


버튼에서 이동할 페이지로 push를 걸어버리면, prepareForSegue에서 무슨짓을 하든 이동해버린다.

뷰컨트롤 하단의 뷰컨트롤러를 끌어서 이동한 페이지와 push로 연결한후 segue에 식별자를 준다.



if(case1){

            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

            UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"ErrorView"];

            

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

            return;

            

        }

  

// case2

    [self performSegueWithIdentifier:@"TargetView"sender:self];

// TargetView는 Segue





NavigationController로 push


 UIViewController *informationView = [storyboard instantiateViewControllerWithIdentifier:@"aaa"];

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



돌아갈땐


[self.navigationController popVieController];




///  커스텀 클래스 연결해 놓은 멤버변수가 설정이 안된다???


Posted by tenn
,

[xcode] Library

iPhone/xcode 2012. 11. 13. 18:56

Project Navigator(왼쪽의 폴더모양) 선택


>Build Phases

>Link Binary With Libraries

> + 클릭해서 라이브러리 추가



Required    :    라이브러리가 없으면 에러

Optional    :    라이브러리가 없으면 무시

-> iOS6에 새로 추가된 라이브러리를 사용하려고 할때, iOS6이하의 버전에서도 에러를 내고 싶지 않다면 Optinal

Posted by tenn
,



UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

Posted by tenn
,





Xcode > Preferences.. 

 Text Editing

Show

Line Number   <-  check

Posted by tenn
,

[obj-c] simple Camera

iPhone 2012. 11. 10. 16:52


1. Project 생성

Single View Application



2. Lib 추가

MobileCoreServices.framework



3. UIViewController(기본적으로 생성되어 있던) UI 구성

사진을 표시할 UIImageView *imageView

카메라로 연결할 버튼 : UIButton *cameraBtn

앨범으로 연결할 버튼 : UIButton *albumBtn


4. 델리게이트

UIImagePickerControllerDelegate

UINavigationControllerDelegate


기본 UIViewController에 추가 


.h >

#import <MobileCoreServices/MobileCoreServices.h>

@interface XXXXXXViewController : UIViewController

<UIImagePickerControllerDelegate, UINavigationControllerDelegate>


@property (assign, nonatomic) BOOL newMedia; 

@property (strong, nonatomic) IBOutlet UIImageView *imageView    <- GUI의 UIImageVIew와 연결


.m > 

@synthesize imageView;

@synthesize newMedia;


5. 버튼의 이벤트 핸들러


이벤트 핸들러를 작성하고, 

GUI의 버튼과 이벤트 핸들러를 연결

.m에서


// 카메라 버튼을 눌렀을 때의 이벤트 핸들러

- (IBAction)useCamera:(id)sender {


    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){

        

        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

        

        imagePicker.delegate = self;

        

        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;


        imagePicker.mediaTypes = [NSArray arrayWithObjects:(NSString *) kUTTypeImage, nil];


        imagePicker.allowsEditing = NO;

        [self presentModalViewController:imagePicker animated:YES];

        newMedia = YES;

        

    }

    

}


//Album버튼을 눌렀을 때의 이벤트 핸들러

- (IBAction)useCameraRoll:(id)sender {

    


    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum]){

        

        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

        imagePicker.delegate = self;

        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

        imagePicker.mediaTypes = [NSArray arrayWithObjects:(NSString *) kUTTypeImage, nil];

        imagePicker.allowsEditing = NO;

        [self presentModalViewController:imagePicker animated:YES];

        newMedia = NO;

        

        

        

    }

     

}





.m에서


- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    [self dismissModalViewControllerAnimated:YES];

    if([mediaType isEqualToString:(NSString *)kUTTypeImage]){

        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

        

        imageView.image = image;

        if (newMedia) UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:finishedSavingWithError:contextInfo:), nil);

    }else if([mediaType isEqualToString:kUTTypeMovie]){

        

        // for movie

    }

    

    

}


- (void) image:(UIImage *) image finishedSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{

    if(error){

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Save failed" message:@"Failed to save image" delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

        [alert show];

    }

}


- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{

    [self dismissModalViewControllerAnimated:YES];

}










Posted by tenn
,







Posted by tenn
,

Button Event




1. storyboard를 열어서 ViewController에 버튼을 추가.



2. Label을 추가.


3. Button의 표시 텍스트와 Label의 정렬을 바꿈.


버튼 : 

라벨 : 


4. 어시스턴트 에디터를 선택.



5. 왼쪽엔 스토리보드, 오른쪽엔 ViewController.h를 표시하고, 버튼과 라벨을 오른쪽 드래그로 ViewController.h에 놓아준다.





6. ViewController.m을 열어서, 이벤트를 핸들링할 메소드를 추가.

    메소드 왼쪽의 원을 왼쪽드래그로 스토리보드에 있는 ViewController의 버튼에 연결해준다.





7. Command + R로 실행.



Posted by tenn
,

storyboard




1. 프로젝트 생성


2. 스토리보드 열기


3. 네비게이션 컨트롤러를 선택해서, 스토리보드에 끌어다 놓음.





4.  네비게이션 컨트롤러의 뒷쪽 뷰컨트롤러는 삭제. 원래 있던 뷰컨트롤러의 화살표를 네비게이션 컨트롤러에 끌어다 놓음.






5. 네이게이션 컨트롤러에서 마우스 오른 클릭으로 드래그하여 뷰컨트롤러에서 놓으면 밑의 팝업메뉴박스가 나온다. Relationship Segue > root view controller를 선택.



6. 스토리보드에 뷰컨트롤러를 추가. 




7. 첫번째 뷰의 네비게이션바에 버튼을 추가. 



8. 추가한 버튼에서 오른클릭 드래그 후, 추가한 뷰컨트롤러에서 놓음. 팝업메뉴박스에서 push를 선택.




9. 네비게이션 바부분을 더블 클릭으로 타이틀을 정해줌.





10. 실행확인 (cmd + R)



Posted by tenn
,

xcode : 4.2.1에서 작성




XCode로 HelloWorld 작성하기





1. 개발할 어플리케이션을 선택


iOS > Application > Single View Application





2. 프로젝트 설정




3. 개발화면이 표시되면 project navigator에서 MainStoryboard.storyboard 선택.




4. 오브젝트 라이브러리에서 라벨을 끌어서 배치. Text를 Hello World로 바꿈.









5. Cmd + R로 시뮬레이터 기동. 결과 확인














Posted by tenn
,

[objc] UIButton

iPhone 2012. 6. 14. 15:25



버튼 코드 생성


    self.startTimeBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    [self.startTimeBtn setTitle:@"start time" forState:UIControlStateNormal];

    self.startTimeBtn.frame = CGRectMake(505011040);



버튼 영역이 모자라면 자동줄바꿈



   //btn : UIButton 

   [self.btn.titleLabel setLineBreakMode:UILineBreakModeWordWrap];


이벤트 핸들링



    [self.startTimeBtn addTarget:self  

                          action:@selector(startTimeBtnAction:)forControlEvents:UIControlEventTouchUpInside];



- (IBAction)startTimeBtnAction:(id)sender {

...

}




title text


[yourButton setTitle:@"your title" forState:UIControlStateNormal];

[yourButton setTitle:@"your title" forState:UIControlStateSelected];

[yourButton setTitle:@"your title" forState:UIControlStateHighlighted];







Button Image 바꾸기


[btn setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];


//[btn setBackgroundImage:image forState:UIControlStateNormal];

//[btn setBackgroundImage:image forState:UIControlStateHighlighted];

// Hightlight없으면 적용이 안됨??? <- 미확인


Posted by tenn
,

[xcode] delegate

iPhone 2012. 4. 24. 16:02

//// FirstView      

액션이 일어남에 따라 핸들링이 있는 부분.

클래스에 델리게이트 선언

액션이 일어나는 클래스의 델리게이션 멤버에  self 대입.


//// SecondView

액션이 일어나는 부분

프로토콜 선언

델리게이트 멤버를가짐





//// First View




// h


#import "SecondViewController.h"


@interface ViewController : UIViewController<SecondViewDelegate>




// m



- (IBAction)btnAction:(id)sender {

    

    SecondViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondView"];

    

    secondViewController.delegate = self;

    

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

    

}








//// SecondView



///h


@protocol SecondViewDelegate

@required

-(void)done:(NSString *)str;

@end


@interface SecondViewController : UIViewController

@property (strong, nonatomic) id<SecondViewDelegate> delegate;



///m

- (IBAction)btnAction:(id)sender {   // btnAction이 핸들링 될때, 델리게이트의 메소드 호출

    [self.delegate done:self.tf.text];

    [self.navigationController popViewControllerAnimated:YES];

}
















Posted by tenn
,

[xcode] 기본 컨트롤.

iPhone 2012. 4. 20. 11:53



//// 버튼


    UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    okBtn.frame = CGRectMake(61, 210, 200, 30);

    [okBtn setTitle:@"OK Button" forState:UIControlStateNormal];


//// 라벨


    UILabel *label = [[UILabel allocinitWithFrame:CGRectMake(1001010024)];

    label.backgroundColor = [UIColor clearColor];

    label.textColor = [UIColor whiteColor];

    label.text = @"label1";

//// 텍스트 필드


    UITextField *tf = [[UITextField allocinitWithFrame:CGRectMake(101010024)]; 

    tf.backgroundColor = [UIColor blueColor];

    tf.borderStyle = UITextBorderStyleLine;

// CGRectMake의 1, 2인수는 시작점. 3,4인수는 프레임의 크기.


    UITextField *tf1 = [[UITextField allocinitWithFrame:CGRectMake(104010024)];    

    tf1.backgroundColor = [UIColor whiteColor];

    tf1.borderStyle = UITextBorderStyleLine;


    [self.view addSubview:tf];

    [self.view addSubview:tf1];


//// 루프로 컨트롤 생성, 접근


    UITextField *textField;

    for (int i=0; i < 5; i++){

        

        textField =

        [[UITextField allocinitWithFrame:CGRectMake(1010 + 30 * i, 10024)];

        textField.borderStyle = UITextBorderStyleLine;

        textField.tag = i;

  //생성된 컨트롤러의 접근을 위해 태그 붙임.

        [self.view addSubview:textField];


    }

    

    UITextField *tf = [self.view viewWithTag:3];

    tf.text = @"tag access";

    [tf addTarget:self action:@selector(endEditing:) forControlEvents:UIControlEventEditingDidEnd];



- (void) endEditing:(id)sender{

//or (IBAction)

//Code만으로 할때는 void리턴타입이어도 됨. 파라메터에 주의.

NSLog(@"endEditing...");

}










Posted by tenn
,





//// section이 복수일때


   //table에 뿌려줄 데이터 sec1, sec2 -> table data

    NSArray *sec1 = [[NSArray alloc] initWithObjects:@"sec1-row1",@"sec1-row2",@"sec1-row3", nil];

    NSArray *sec2 = [[NSArray alloc] initWithObjects:@"sec2-row1",@"sec2-row2", nil];

    

    tabledata = [[NSArray alloc] initWithObjects:sec1,sec2, nil];


...




// cell 세팅

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

{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    

    // Configure the cell...

    

    if(cell == nil){

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

    }


    if(indexPath.section == 0){

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

    }else if(indexPath.section == 1){

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

    }

    

    return cell;

}


//section 갯수

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

#warning Potentially incomplete method implementation.

    // Return the number of sections.

    return self.tabledata.count;

}


// Record 갯수 (section별로)

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

{

#warning Incomplete method implementation.

    // Return the number of rows in the section.

    

    if(section == 0){

        return [[self.tabledata objectAtIndex:0] count];

    }else if(section == 1){

        return [[self.tabledata objectAtIndex:1] count];        

        

    }

    

}



// Header와 Footer

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    if(section == 0){

        return @"section1";

    }else{

        return @"Section2";

    }

}



- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {

    if(section == 0){

        return @"section1";

    }else{

        return @"Section2";

    }

}


Posted by tenn
,

[obj-c] View 이동

iPhone 2012. 4. 13. 12:01



Push


UIViewController *detailViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailView"];

//스토리보드에서 식별자 DetailView인 컨트롤러에 포인터 지정


[self.navigationController pushViewController:detailViewController animated:true];

//push로 뷰이동



Modal에서 돌아가기


[self dismissModalViewControllerAnimated:YES];


Posted by tenn
,

[obj-c] File

iPhone 2012. 4. 6. 17:34


//// 어플리케이션의 하위디렉터리
Documents
Library
tmp

NSTemporaryDirectory();  //tmp디렉터리 경로

if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){}  //파일 존재여부 확인

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Apps" ofType:@"plist"];
//Resources폴더에서 프로퍼티 리스트 로드

//File Path = app's documents folder

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMaskYES);

      NSString *documentsDir = [paths objectAtIndex:0];

      NSString *fileName = 

            [documentsDir stringByAppendingPathComponent:@"data2.txt"];


//File write

    NSMutableArray *array = [[NSMutableArray allocinit];

    [array addObject:@"Text1"];

    [array addObject:@"Text2"];

    [array writeToFile:fileName atomically:YES];  



//File read

if ([[NSFileManager defaultManagerfileExistsAtPath:fileName]){

        NSArray *array = [[NSArray allocinitWithContentsOfFile: fileName];

        NSLog(@"%@",array);

 }

//// Image File Save



- (IBAction)saveAction:(id)sender {

    NSMutableArray *array = [[NSMutableArray alloc] init];

    [array addObject:UIImagePNGRepresentation(self.imageView.image)];

    [array writeToFile:self.fileName atomically:YES];  

    ALERT(@"FileSave", @"Image Saved.");

}


- (IBAction)loadAction:(id)sender {

    if ([[NSFileManager defaultManager] fileExistsAtPath:fileName]){

        NSArray *array = [[NSArray alloc] initWithContentsOfFile: fileName];

        UIImage *image = [UIImage imageWithData:[array objectAtIndex:0]];

        self.imageView.image = image;

    }




Posted by tenn
,





// 기본


UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"Hello World"

                                                    message:@"iphone, here I come!"

                                                   delegate:self

                                          cancelButtonTitle:@"OK"

                                          otherButtonTitles:nil];

[alert show];

[alert release];

////사용자가 버튼 누를때까지 대기


UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Contacting Server\nPlease Wait..."

message:nil

delegate:nil

cancelButtonTitle:@"OK"

otherButtonTitles:nil];

[alert show];

while ((!alert.hidden) && (alert.superview != nil)) {

[[NSRunLoop currentRunLoop] limitDateForMode:NSDefaultRunLoopMode];

}

[alert release];

////Macro

#define ALERT(X,Y) {UIAlertView *alert = [[UIAlertView alloc] initWithTitle:X message:Y delegate:self cancelButtonTitle:@"OK"otherButtonTitles: nil];[alert show];[alert release];}

//// Yes/No alert view

- (IBAction)deleteBtn:(id)sender {

    

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"削除"

                                                    message:@"削除しますか?"

                                                   delegate:self

                                          cancelButtonTitle:@"はい"

                                          otherButtonTitles:@"いいえ", nil];

    [alert show];

    [alert release];

    

}


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

NSLog(@"%d", buttonIndex);

    

}




Posted by tenn
,