.h


<UINavigationControllerDelegate, UIImagePickerControllerDelegate>




////////////

.m




- (IBAction)tapBtn:(id)sender {

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

    pickerLibrary.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [pickerLibrary setAllowsEditing:YES];

    pickerLibrary.delegate = self;

    

    //[self presentModalViewController:pickerLibrary animated:YES];

   //deprecated in iOS6

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

    

}


- (void) imagePickerController:(UIImagePickerController * )picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{

    

    targetImage = image; 

    

    [self dismissViewControllerAnimated:YES completion:nil];    

    

}




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

    

    [self dismissViewControllerAnimated:YES completion:nil];   

    

    

}









Posted by tenn
,








    UITapGestureRecognizer *pressGesture =

    [[UITapGestureRecognizer alloc] initWithTarget:self

                                                  action:@selector(doSomethingMethod)];

    

    

    [targetView addGestureRecognizer:pressGesture];




Posted by tenn
,

[objc] GPUImage framework

iPhone 2013. 1. 30. 17:23




GPUImage framework


https://github.com/BradLarson/GPUImage






< framework import > 


GPUImage framework를 다운로드 받아서, 임포트할 프로젝트에 둔다.


xcode에서 프로젝트 Frameworks에 GPUImage.xcodeproj를 드래그


GPUImage를 빌드 -> product에 libGPUImage.a 생성


BuildPhase > Target Dependencies 에 libGPUImage를 추가

BuildPhase > Link Binary Libraries 에 다음의 프레임워크추가

CoreMedia, CoreVideo, OpenGLES, AVFoundation, QuatzCore

libGPUImage도 라이브러리에 추가


BuildSetting > Search paths > header search pathes

GPUImage framework의 루트를 지정(xcodeproj가 있는 폴더)

recursive로 지정

Header Search pathes에 지정하면 Debug와 Release에 같은 값이 지정된다.

예 > GPUImage/framework  


코딩할 문서에서 

#import "GPUImage.h"  <- 자동완성이 안되면 header search path지정이 잘못된 것


코딩... 코딩... 코딩...




Introducing the GPUImage framework

http://sunsetlakesoftware.com/2012/02/12/introducing-gpuimage-framework



간단한 예제 : 감마필터 적용시키기



    CGRect mainScreenFrame = [[UIScreen mainScreen] applicationFrame];

GPUImageView *primaryView = [[GPUImageView alloc] initWithFrame:mainScreenFrame];

self.view = primaryView;

    

    UIImage *inputImage = [UIImage imageNamed:@"x.png"];

    

    GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:inputImage];

    

    GPUImageGammaFilter *g = [[GPUImageGammaFilter alloc] init];

    [g setGamma:0.2];

    

    [picture addTarget:g];

    

    [g addTarget:primaryView];

    

    [picture processImage];





Posted by tenn
,

해상도등 스펙비교 찾으려면 귀찮으므로 메모.



아이폰비교



아이팟비교


Posted by tenn
,

커스텀 스플레시화면을 위해 뷰를 현재 화면에 덮어서 표시하고 싶었는데,


원래 소스가 self.view에 이상한 짓을 많이 해서 addSubView해서 bringSubviewToFront해도 표시가 안되서


AppDelegate의 window를 잡아와서 얹어버렸다.



UIView *target = [[UIApplication sharedApplication].windows objectAtIndex:0];


UIView *vv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, target.bounds.size.width, target.bounds.size.height)];


vv.backgroundColor = [UIColor redColor];


[target addSubview:vv];




    

Posted by tenn
,

[objc] 원의 좌표

iPhone 2013. 1. 9. 11:26


애니메이션의 원의 경로로 움직이고 싶을때 등.


radius : 원의 반지름

degree : 각도


x = 원의 중심이 될 x좌표 + cos(각도) * 반지름

y = 원의 중심이 될 y좌표 + sin(각도) * 반지름



ex >

    float x = self.view.center.x + cos(degree) * radius;

    float y = self.view.center.y + sin(degree) * radius;

Posted by tenn
,



iOS6


//UINavigationController에서 


- (BOOL)shouldAutorotate {

    return NO;

}



http://stackoverflow.com/questions/12777474/ios-6-app-is-rotating-even-with-shouldautorotateno





Posted by tenn
,



 NSInteger rand = arc4random() % 10 +1;

// 1〜10


Posted by tenn
,



디바이스 종류구분을 height로 할 때,

[UIScreen mainScreen].bounds.size.height == 568



잘되던 코드가 splash image를 삭제하자 동작하지 않게 되었다.


height가 ipod touch 5세대에서 480이 나오는 것.


splash image를 원래대로 돌리자 정상.


어쩔수 없이 크기가 같은 검은 덤프이미지를 넣어서 해결.

Posted by tenn
,

[objc] iOS App Lifecycle

iPhone 2012. 12. 18. 14:13













Posted by tenn
,


Gyroscope




#import <CoreMotion/CoreMotion.h>


    self.motionManager = [[CMMotionManager alloc] init];



    //Gyroscope

    if([self.motionManager isGyroAvailable])

    {

        /* Start the gyroscope if it is not active already */ 

        if([self.motionManager isGyroActive] == NO)

        {

            /* Update us 2 times a second */

            [self.motionManager setGyroUpdateInterval:1.0f / 2.0f];


            /* And on a handler block object */


            /* Receive the gyroscope data on this block */

            [self.motionManager startGyroUpdatesToQueue:[NSOperationQueue mainQueue]

             withHandler:^(CMGyroData *gyroData, NSError *error)

            {

                NSString *x = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.x];

                self.gyro_xaxis.text = x;


                NSString *y = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.y];

                self.gyro_yaxis.text = y;


                NSString *z = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.z];

                self.gyro_zaxis.text = z;

            }];

        }

    }

    else

    {

        NSLog(@"Gyroscope not Available!");

    }

}


http://stackoverflow.com/questions/7135934/ios-gyroscope-api





Posted by tenn
,



UITapGestureRecognizer

탭(몇번이든)

UIPinchGestureRecognizer

(두손가락으로 집어 벌리기 오므리기)

UIPanGestureRecognizer

Panning or dragging

UISwipeGestureRecognizer

넘기기 (어떤 방향이든)

UIRotationGestureRecognizer

Rotating (fingers moving in opposite directions)

UILongPressGestureRecognizer

길게누르기



Posted by tenn
,

[objc] UISwitch

iPhone 2012. 12. 7. 13:51




UISwitch의 설정값을 가지는 것은

on   ← 요놈이다.(BOOL)






[swc setOn:YES animated:YES];   //swc : UISwitch



UISwitch를 이벤트처리 메소드와 연결해두면, 이벤트처리 메소드를 먼저 실행하고, 스위치가 바뀌는 애니메이션이 보이게 된다. 이벤트처리에 선택된 변수 UISwitch.on을 설정을 바꾸기 전으로 되돌려두면 애니메이션은 일어나지 않는다. 





Posted by tenn
,

[obc-c] device id, UDID

iPhone 2012. 12. 6. 20:13



UIDevice *myDevice = [UIDevice currentDevice];

NSString *deviceUDID = [myDevice uniqueIdentifier];


위의 방법은 애플의 정책에 의해 deprecated되어, iOS5부터 UDID를 사용하는 것은

권장할만한 일이 아니게 되었다.


대신에 단말을 구분할 방법으로 UUID(Universal Unique ID)를 생성할 방법을 제공한다.

대신에 UserDefaults로 생성된 UUID가 항상 같은 값이도록 관리할 필요가 있는 듯하다.


CFUUIDRef UUIDRef = CFUUIDCreate(kCFAllocatorDefault);

CFStringRef UUIDSRef = CFUUIDCreateString(kCFAllocatorDefault, UUIDRef);

    



Posted by tenn
,



* BOOL -> Object화


[NSNumber numberWithBool:<#(BOOL)#>]



*int, float, double -> Object화


[NSNumber number〜...  ]



*NSString -> NSNumber

[NSNumber numberWithInteger:[theString integerValue]];

http://stackoverflow.com/questions/3163652/how-to-convert-nsstring-to-nsnumber-without-using-numberfromstring


Posted by tenn
,

[obj-c] Local Notification

iPhone 2012. 12. 6. 15:06





<< AppDelegate >>


/**      Local Notificaiton      **/


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

{

    

    

    NSLog(@"didFinishLaunchingWithOptions");

    

    UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

    

    if (notification) {

    //어플리케이션이 시작될때, 노티피케이션에 의한것?

    //어플리케이션이 액티브이지 않을때, 노티피케이션에 의해 불린다면

        

        [self showAlarm:notification.alertBody];

        NSLog(@"AppDelegate didFinishLaunchingWithOptions");

        application.applicationIconBadgeNumber = 0;

    }

    

    [self.window makeKeyAndVisible];

    

    

    

    // Override point for customization after application launch.

    return YES;

}




- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

    //어플리케이션이 액티브일때, 노티피케이션 수신

    

    [self showAlarm:notification.alertBody];

    application.applicationIconBadgeNumber = 0;

    NSLog(@"AppDelegate didReceiveLocalNotification %@", notification.userInfo);

    

}


- (void)showAlarm:(NSString *)text {

    

    

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alarm"

                                                        message:text delegate:nil

                                              cancelButtonTitle:@"OK"

                                              otherButtonTitles:nil];

[alertView show];

}







<< 노티피케이션을 등록할 곳 >>



    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    

    UILocalNotification *localNotification = [[UILocalNotification alloc] init];

    

    // 10초후 노티피케이션 등록

    NSDate *now = [NSDate date];

    NSDate *dateToFire = [now dateByAddingTimeInterval:5];

    

    NSLog(@"now time: %@", now);

    NSLog(@"fire time: %@", dateToFire);

    

    

    localNotification.fireDate = dateToFire;

    localNotification.alertBody = @"Time to get up!";

    localNotification.soundName = UILocalNotificationDefaultSoundName;

    localNotification.applicationIconBadgeNumber = 1; // increment

   

     NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Object 1", @"Key 1", @"Object 2", @"Key 2", nil];

    

    localNotification.userInfo = infoDict;

    

    

     

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];







Posted by tenn
,

File Merge 간단 사용법



1. xcode의 상단의 메뉴바에서

Xcode > Open Developer Tool > FileMerge


2. 병합할 파일을 Left… Right…에 드래그 해서 설정.

    마지의 결과를 기록할 파일을 Merge에 비교할 파일을 Ancestor에 설정. 


3. 변경부분중 병합하고 싶은 부분을 선택하고 오른쪽하단의 Action버튼을 눌러 병합결정을 한다.

    선택된 부분쪽으로 화살표가 향한다.


4. File > Save Merge As... 로 저장

   Merge를 지정한 경우는 Cmd + S 만으로 저장이 된다.



xcodeproj 파일안의 project.pbxproj파일을 마지할때 편리


Posted by tenn
,

[obj-c] mach-0 linker error

iPhone 2012. 12. 3. 13:56

소스를 프로젝트에 추가도 안해주고 헤더파일을 import 하니 발생했다.

Posted by tenn
,

[objc] UILabel

iPhone 2012. 11. 30. 17:27




Text 가운데 정렬


       label.textAlignment = UITextAlignmentCenter;






라벨의 개행



내용에 개행문자 \n 삽입

라벨을 라인브레이크 모드로 지정


http://stackoverflow.com/questions/2312899/how-to-add-line-break-for-uilabel








Posted by tenn
,
NSUserDefaults

App을 재빌드 해도, 초기화 되지 않음.





간단히 쓰기



NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];


NSString *value = [ud objectForKey:@"key"];


[ud setObject:@"value" forKey:@"key"];


[ud synchronize];






그외


http://blog.naver.com/PostView.nhn?blogId=legendx&logNo=40097971685



Posted by tenn
,






날짜 형식을 다른 형식으로 바꾸기. 

1999-10-12 11:10:22.111   ->  99.10.12 11:10



NSString *dateString = @"1999-10-12 11:10:22.111";

      NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];

        [dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

        NSDate *date = [dateFormat dateFromString:dateString];

        [dateFormat setDateFormat:@"yy/MM/dd HH:mm"];

        NSString *stringFromDate = [dateFormat stringFromDate:date];

Posted by tenn
,

[obj-c] UIAlertDelegate

iPhone 2012. 11. 30. 11:13




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

        if(buttonIndex == kNo) {
        } else {
            //Close by suspending...
            [[UIApplication sharedApplication] suspend];
        }
    }





http://stackoverflow.com/questions/11034369/objective-c-derived-uialertview-ok-button

Posted by tenn
,

[objc] UIWebView

iPhone 2012. 11. 29. 20:11

UIWebView 




Delegate


UITableView에서 커스텀된 Cell에 UIWebView를 넣었는데 link가 작동안하는 현상이 있었다.


커스텀된 Cell에서<UIWebViewDelegate>를 델리케이트 추가해주고,

xib의 delegate를 연결한 후, 링크가 작동.



String HTML의 표시



loadData


NSString *html = @" <font color='red'><b> Detail... </font> <br>";

    

NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];

    

[self.webView loadData:data MIMEType:@"text/plain" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"nil"]];



iOS6.1, iOS6.0에서 동작확인.

iOS5.1.1에서 동작안함.



loadHTMLString


...

[self.webView loadHTMLString:html baseURL:nil];



iOS6.0, iOS5.1.1에서 동작확인.




UIWebView에 배경화면 설정하기



배경화면을 넣은 UIImageView를 UIWebView뒤에 배치.

UIWebView의 BackgroundColor를 clearColor, Opaque = NO로 지정.



폰트 사이즈의 지정 (px)


<span style=font-size:14px;color:#000000>

...

</span>








iOS5에서는 autolayout이 없으므로

다음 설정이 필요하다.


webView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

 webView.autoresizesSubviews = YES;




loadHTMLString:baseURL: 는 로딩하는데 시간이 걸리므로 

그전에 스크립트로 높이등을 구하려고 해도, 바른값을 취득할수 없다.

UIWebView의 로딩이 끝나면 webViewDidFinishLoad:가 호출된다.








Posted by tenn
,

[obj-c] CGPoint

iPhone 2012. 11. 28. 11:47



CGPoint point = CGPointMake(10.0f, 10.0f);

Posted by tenn
,

[obj-c] thread,

iPhone 2012. 11. 28. 11:28

Thread의 기초


http://maclove.pe.kr/30




performSelector의 셀렉터와 인수




@implementation ClassForSelectors
- (void) fooNoInputs {
    NSLog(@"Does nothing");
}
- (void) fooOneIput:(NSString*) first {
    NSLog(@"Logs %@", first);
}
- (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second {
    NSLog(@"Logs %@ then %@", first, second);
}
- (void) performMethodsViaSelectors {
    [self performSelector:@selector(fooNoInputs)];
    [self performSelector:@selector(fooOneInput:) withObject:@"first"];
    [self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first" withObject:@"second"];
}
@end


http://stackoverflow.com/questions/1018195/objective-c-calling-selectors-with-multiple-arguments


Posted by tenn
,

[obj-c] CALayer

iPhone 2012. 11. 22. 18:46









.bounds = CGRectMake(0,0,50,50);   // 크기

.position = self.view.center;    // 위치

.cornerRadius = 30;  // 0 사각형, 100은 원

.borderColor = [UIColor blueColor].CGColor; // Color

      .borderWidth = 0.5;   // 선굵기

      addSublayer:   //SubLayer추가


    [self.view.layer addSublayer:calayer];    // 뷰에 레이어 배치



ref : http://soooprmx.com/wp/archives/2509



CALayer 에 이미지 그리기


 [calayer setContents:(id)[[UIImage imageNamed:@"icon.png"] CGImage]];






Posted by tenn
,

[obj-c] UIImageView

iPhone 2012. 11. 21. 16:53


UIImageView 회전시키기


UIImageView *imageView = [UIImageView imageViewWithImage:srcImage];   //srcImage : UIImage

imageView.transform = CGAffineTransformMakeRotation(90*M_PI /180);    // 90 degree

      





Posted by tenn
,



LongPress의 down과 up만 체크



 UILongPressGestureRecognizer *longPressGesture =

        [[UILongPressGestureRecognizer allocinitWithTarget:self

                                                action:@selector(handleLongPress:)];


          


[targetView addGestureRecognizer:longPressGesture];



.....


// Handler

- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer {

    CGPoint location = [recognizer locationInView:[recognizer.view superview]];

    

    if (recognizer.state == UIGestureRecognizerStateBegan) {

        NSLog(@" long press start ... ");

    }else if(recognizer.state == UIGestureRecognizerStateEnded){

        NSLog(@" long press ended ... ");


    }

      

}



Posted by tenn
,

[obj-c] UIScrollView

iPhone 2012. 11. 21. 14:20





http://greenalice.tistory.com/225








UIScrollView에서의 touch 핸들링


http://blog.naver.com/PostView.nhn?blogId=sinaeyo&logNo=30093493220

Posted by tenn
,

[obj-c] NSArray

iPhone 2012. 11. 21. 09:59



NSArray 초기화


 NSArray * array = [NSArray arrayWithObjects:obj1, obj2, obj3, nil]; 

Posted by tenn
,