2014년 11월 20일 목요일

keyboard 에서 enter 키 누르면 키보드 숨기기


UITextField 의 경우

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        [self.view endEditing:YES];
    }
    return YES;
}



UITextView 의 경우


#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [self.view endEditing:YES];
    }
    return YES;

}

2014년 11월 3일 월요일

최상위 View Controller 가져오기



+ (UIViewController*)topMostViewController {
    UIViewController *topMostViewController = nil;
    
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        topMostViewController = navigationController.visibleViewController;
    } else if (rootViewController.presentedViewController) {
        topMostViewController = rootViewController.presentedViewController;
    } else if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        topMostViewController = tabBarController.selectedViewController;
    } else
        topMostViewController = rootViewController;
    
    return topMostViewController;

}

2014년 10월 15일 수요일

#define

#define IS_IPAD    (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

#define POINT(_INDEX_) [(NSValue *)[points objectAtIndex:_INDEX_] CGPointValue]

#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))

#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:r/255.f green:g/255.f blue:b/255.f alpha:a]

#define ColorWithHexa(rgbValue) [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 \
                                        green:((rgbValue & 0xFF00) >> 8)/255.0 \

                                        blue:(rgbValue & 0xFF)/255.0 alpha:1.0]; \

#define RESIZABLE(_VIEW_) [_VIEW_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth]

#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))

// check iOS version
#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)


#define DOCUMENTS_DIR ([NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject])
#define SCREEN_WIDTH ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height)
#define SAFE_RELEASE(obj) ([obj release], obj = nil)
#define SAFE_TIMER_RELEASE(obj) ([obj invalidate]; [obj release]; obj = nil)
#define SAFE_ASSIGN(obj, expr) ([(expr) retain], [obj release], obj = (expr))

2014년 10월 9일 목요일

@ 매크로


1.
    NSString *string = @"<#string#>"

2.  
    id express = @(<#expression#>)

  (ex)
    NSInteger idx = 40;
    NSString *idxString = [@(idx) stringValue];

3.    
    NSArray *array =  @[<#objects, ...#>]

4.    
    @autoreleasepool {
        <#statements#>
    }

5.    
    char[] chars =  @encode(<#type-name#>)

6.    
    Protocol *protocol = @protocol(<#protocol-name#>)

7.    
    SEL sel = @selector(<#selector#>)

8.    
    @throw <#expression#>
    
9.
    NSDictonary *dic = @{<#key#>: <#object, ...#>}
    
10.
    @try {
        <#Code that can potentially throw an exception#>
    }
    @catch (NSException *exception) {
        <#Handle an exception thrown in the @try block#>
    }
    @finally {
        <#Code that gets executed whether or not an exception is thrown#>

    }

11. structure

    CGSize theSize = {
        .width = 100.f,
        .height = 100.f,
    };
    
    CGRect theRect = {
        {.x = 10.f, .y= 10.f},
        {.width = 200.f, .height = 200.f}
    };

2014년 10월 1일 수요일

UIAlertView & Block function

source

//
//  CustomUIAlertView.m
//  patternpie
//
//  Created by MYUNG GU KIM on 10/2/14.
//  Copyright (c) 2014 piestudio. All rights reserved.
//

#import "CustomUIAlertView.h"

@implementation CustomUIAlertView

- (void)showWithBlock:(void (^)(int selectedIndex))complete
{
    self.delegate = self;
    ptrComplete = complete;
    [self show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    ptrComplete((int)buttonIndex);
}


@end




header 

//
//  CustomUIAlertView.h
//  patternpie
//
//  Created by MYUNG GU KIM on 10/2/14.
//  Copyright (c) 2014 piestudio. All rights reserved.
//

#import <UIKit/UIKit.h>

void (^ptrComplete)(int);

@interface CustomUIAlertView : UIAlertView <UIAlertViewDelegate>
{
}
- ( void )showWithBlock: ( void ( ^ )( int selectedIndex) )complete;
@end





using


[[[CustomUIAlertView alloc] initWithTitle:nil message:@"Do you want Challenge?" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil] showWithBlock:^(int selectedIndex) {
            NSLog(@"You selected button %d", selectedIndex);
        }];




2014년 9월 30일 화요일

random


1.  0~10 까지의 랜덤 숫자

uint32_t random = arc4random_uniform(11);

2.  50~100 까지의 랜덤 숫자

uint32_t random = arc4random_uniform(51)+50;




3.  랜덤 숫자

unsigned int random = arc4random();


4. 컬러값 랜덤으로 가져오기

static func randomBackgroundColor() -> UIColor {
        let colors = [UIColor.rgb(5, 200, 123), UIColor.rgb(176, 158, 145), UIColor.rgb(106, 97, 248), UIColor.rgb(33, 173, 254), UIColor.rgb(249, 135, 40)]
        let randomIndex = Int(arc4random_uniform(UInt32(colors.count)))
        return colors[randomIndex]

    }

2014년 9월 23일 화요일

시, 분, 초 계산 방법


   CFTimeInterval _ticks;




    _ticks += 0.1;
    double seconds = fmod(_ticks, 60.0);
    double minutes = fmod(trunc(_ticks / 60.0), 60.0);
    double hours = trunc(_ticks / 3600.0);
    self.timerLabel.text = [NSString stringWithFormat:@"%02.0f:%02.0f:%04.1f", hours, minutes, seconds];
    

    NSLog(@"tick = %f text = %@", _ticks, self.timerLabel.text);





2014-09-24 02:59:49.241 TabbedBanner[961:60b] tick = 0.100000 text = 00:00:00.1
2014-09-24 02:59:49.341 TabbedBanner[961:60b] tick = 0.200000 text = 00:00:00.2
2014-09-24 02:59:49.441 TabbedBanner[961:60b] tick = 0.300000 text = 00:00:00.3
...
2014-09-24 02:59:53.141 TabbedBanner[961:60b] tick = 4.000000 text = 00:00:04.0
2014-09-24 02:59:53.241 TabbedBanner[961:60b] tick = 4.100000 text = 00:00:04.1
2014-09-24 02:59:53.341 TabbedBanner[961:60b] tick = 4.200000 text = 00:00:04.2
2014-09-24 02:59:53.441 TabbedBanner[961:60b] tick = 4.300000 text = 00:00:04.3
...
2014-09-24 03:03:35.186 TabbedBanner[961:60b] tick = 224.900000 text = 00:03:44.9
2014-09-24 03:03:35.286 TabbedBanner[961:60b] tick = 225.000000 text = 00:03:45.0
2014-09-24 03:03:35.386 TabbedBanner[961:60b] tick = 225.100000 text = 00:03:45.1
2014-09-24 03:03:35.486 TabbedBanner[961:60b] tick = 225.200000 text = 00:03:45.2
2014-09-24 03:03:35.586 TabbedBanner[961:60b] tick = 225.300000 text = 00:03:45.3
2014-09-24 03:03:35.686 TabbedBanner[961:60b] tick = 225.400000 text = 00:03:45.4

2014년 8월 13일 수요일

UITextField 의 text 가 영인지 체크하는 방법




- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSRange textFieldRange = NSMakeRange(0, [textField.text length]);
    if (NSEqualRanges(range, textFieldRange) && [string length] == 0) {
        [_keywordClearButton setHidden:YES];
    } else
        [_keywordClearButton setHidden:NO];
    
    return YES;

}

2014년 8월 5일 화요일

rotate 360 degree


1)

CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
    fullRotation.fromValue = [NSNumber numberWithFloat:0];
    fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
    fullRotation.duration = .3f;
    fullRotation.repeatCount = 1;

    [self.layer addAnimation:fullRotation forKey:@"360"];

2)

if(rotationCount == 3) {
        [UIView animateWithDuration:.4f delay:0.f usingSpringWithDamping:.5f initialSpringVelocity:0.f options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionBeginFromCurrentState animations:^{
            [_thumbnailImage setTransform:CGAffineTransformRotate(_thumbnailImage.transform, M_PI_2)];
        } completion:^(BOOL finished) {
            if (finished) {
                return;
            }
        }];
    }
    else {
        
        [UIView animateWithDuration:.2f animations:^{
            [_thumbnailImage setTransform:CGAffineTransformRotate(_thumbnailImage.transform, M_PI_2)];
        } completion:^(BOOL finished) {
            [self rotateAnimation];
        }];
        
    }
    
    rotationCount++;


3)

[UIView animateKeyframesWithDuration:.8f delay:0.0 options:UIViewKeyframeAnimationOptionCalculationModeLinear|UIViewKeyframeAnimationOptionBeginFromCurrentState animations:^{
        
        // push the from- view to the back
        [UIView addKeyframeWithRelativeStartTime:0.0f relativeDuration:0.4f animations:^{
            [_thumbnailImage setTransform:CGAffineTransformRotate(_thumbnailImage.transform, M_PI_2)];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.2f relativeDuration:0.4f animations:^{
            [_thumbnailImage setTransform:CGAffineTransformRotate(_thumbnailImage.transform, M_PI_2)];
        }];
        
        // slide the to- view upwards. In his original implementation Tope used a 'spring' animation, however
        // this does not work with keyframes, so we siulate it by overshooting the final location in
        // the first keyframe
        [UIView addKeyframeWithRelativeStartTime:0.6f relativeDuration:0.2f animations:^{
            [_thumbnailImage setTransform:CGAffineTransformRotate(_thumbnailImage.transform, M_PI_2)];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.8f relativeDuration:0.2f animations:^{
            [_thumbnailImage setTransform:CGAffineTransformRotate(_thumbnailImage.transform, M_PI_2)];
        }];
        /*
        [UIView addKeyframeWithRelativeStartTime:1.f relativeDuration:0.4f animations:^{
            [_thumbnailImage setTransform:CGAffineTransformRotate(_thumbnailImage.transform, -(M_PI_2))];
        }];
        
        [UIView addKeyframeWithRelativeStartTime:.9f relativeDuration:0.2f animations:^{
            [_thumbnailImage setTransform:CGAffineTransformRotate(_thumbnailImage.transform, M_PI_4)];
        }];
        [UIView addKeyframeWithRelativeStartTime:1.4f relativeDuration:0.2f animations:^{
            [_thumbnailImage setTransform:CGAffineTransformRotate(_thumbnailImage.transform, -(M_PI_4))];
        }];
        [UIView addKeyframeWithRelativeStartTime:1.8f relativeDuration:0.2f animations:^{
            [_thumbnailImage setTransform:CGAffineTransformIdentity];
        }];*/
        
        
    } completion:^(BOOL finished) {
    }];

flip 360 degree


1) horizontally flip


_bodyView.transform = CGAffineTransformScale(_bodyView.transform, 1, -1);
    
    [UIView animateWithDuration:.5f delay:0 usingSpringWithDamping:.3f initialSpringVelocity:70.f options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
        
        _bodyView.transform = CGAffineTransformScale(_bodyView.transform, 1, -1);
        
    } completion:^(BOOL finished) {

    }];

2014년 7월 18일 금요일

UICollectionView 에서 orientation이변경할때 landscape, portrait에 따라서 cell 사이즈 자역스럽게 변경하기

1.  orientation이 바뀌었을때 새로운 layout을 변경 적용.

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
...
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0.f;
    layout.minimumLineSpacing = 0.f;
    layout.sectionInset = UIEdgeInsetsZero;
    [self.collectionView setCollectionViewLayout:layout animated:YES];
    [_collectionView scrollToItemAtIndexPath:currentIndexPath             atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

2. UICollectionView delegate 에서 함수 사이즈 return

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) {
        return CGSizeMake(320.f, 180.f);
    }
    return CGSizeMake(568.f, 320.f);
}

2014년 7월 2일 수요일

UISlider 커스텀

이미지의 사이즈에 맞게 slider의 높이 및 thumb 이미지 교체, 및 slider 의 track을 이미지로 대체.



UIImage *minImage = [[UIImage imageNamed:@"slider_minimum.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
    UIImage *maxImage = [[UIImage imageNamed:@"slider_maximum.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
    UIImage *thumbImage = [UIImage imageNamed:@"sliderhandle.png"];
    
    [[UISlider appearance] setMaximumTrackImage:maxImage forState:UIControlStateNormal];
    [[UISlider appearance] setMinimumTrackImage:minImage forState:UIControlStateNormal];
    [[UISlider appearance] setThumbImage:thumbImage forState:UIControlStateNormal];



2014년 6월 2일 월요일

Button array에 있는 객체의 속성을 한번에 바꾸는 방법.


예제 1)
[_arrowButtons setValue:@NO forKeyPath:@"userInteractionEnabled"];


예제2)
[self.starImageViews setValue:@NO forKey:@"highlighted"];

2014년 5월 28일 수요일

append items to UITableView or UICollectionView


// from stack overflow with UITableView

// build the index paths for insertion
    // since you're adding to the end of datasource, the new rows will start at count
    NSMutableArray*indexPaths =[NSMutableArray array];
    NSInteger currentCount = self.datasource.count;
    for(int i =0; i < dataToAdd.count; i++)
    {
        [indexPaths addObject:[NSIndexPath indexPathForRow:currentCount+i inSection:0]];
    }
    // do the insertion
    [self.dataSource addObjects:dataToAdd];
    // tell the table view to update (at all of the inserted index paths)
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];

    [self.tableView endUpdates];



// in my real code with UICollectionView

- (void)getMoreServerData
{
// 새로운 아이템을 컬렉션의 끝에 추가
NSMutableArray *indexPaths = [NSMutableArray array];
                NSInteger currentCount = items.count;
                for (int i = 0; i < model.storesModelArray.count; i++) {
                    [indexPaths addObject:[NSIndexPath indexPathForRow:currentCount+i inSection:0]];
                }
                [items addObjectsFromArray:model.storesModelArray];
                [self.collectionView insertItemsAtIndexPaths:indexPaths];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// 리스트의 마지막에 도착한 경우 attach data
    if (scrollOffset + scrollView.frame.size.height == scrollView.contentSize.height)
    {
        [self getMoreServerData];
    }
}

2014년 5월 17일 토요일

grid crop with uiimage

이미지를 grid 형태로 잘라서 view에 add하는 예제.


- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage *scaledImage = [self scaleWithImage:[UIImage imageNamed:@"37.jpg"] scaledToSize:self.view.frame.size];
    self.originalImageView = [[UIImageView alloc] initWithImage:scaledImage];
    [self prepareSlices:10 :10];
}

-(void)prepareSlices:(uint)row :(uint)col
{
    float flagX = _originalImageView.image.size.width / _originalImageView.frame.size.width;
    float flagY = _originalImageView.image.size.height / _originalImageView.frame.size.height;
    
    float _width    = _originalImageView.frame.size.width / col;
    float _height   = _originalImageView.frame.size.height / row;
    
    float _posX = 0.0;
    float _posY = 0.0;
    
    for (int i = 1; i <= row * col; i++) {
        
        UIImageView *croppedImageVeiw = [[UIImageView alloc] initWithFrame:CGRectMake(_posX, _posY, _width, _height)];
        UIImage *img = [self getCropImage:CGRectMake(_posX * flagX,_posY * flagY, _width * flagX, _height * flagY)];
        croppedImageVeiw.image = img;
        
        croppedImageVeiw.layer.borderColor = [[UIColor whiteColor] CGColor];
        croppedImageVeiw.layer.borderWidth = 1.0f;
        
        [self.view addSubview:croppedImageVeiw];
        
        _posX += _width;
        
        if (i % col == 0) {
            _posX = 0;
            _posY += _height;
        }
    }
}

-(UIImage*)getCropImage:(CGRect)cropRect
{
    CGImageRef image = CGImageCreateWithImageInRect([_originalImageView.image CGImage],cropRect);
    UIImage *cropedImage = [UIImage imageWithCGImage:image];
    CGImageRelease(image);
    return cropedImage;

}

- (UIImage *)scaleWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


2014년 5월 10일 토요일

UIView가 화면에 추가되서 보여지는지 안보여지고있는지 체크하는 방법

UIView.window를 체크하면 됨.

<예제>
MyUIViewController.h

UIView *popupView;



MyUiViewController.m
..
popupView = [UIView alloc] init];
[self.view addSubView:popupView];

if(popupView.Window  != nil)
    NSLog(@"you can see popup now");



....

[popupView removeFromSuperView];
if(popupView.Window  == nil)
    NSLog(@"you can't see popup now");


2014년 5월 9일 금요일

uiview 터시하면 keyboard 사라지게 하는 방법

UIView 의 - (BOOL)endEditing:(BOOL)force  함수를 사용하면 됨.


예제)

MyViewController.m
...
..
[self.view endEditing:NO];

2014년 5월 2일 금요일

string에서 keyword를 찾아 빨간색으로 표시하기




// search matching keyword
    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:searchKeyword
                                  options:NSRegularExpressionCaseInsensitive
                                  error:nil];
    [regex enumerateMatchesInString:fullString options:0 range:NSMakeRange(0, [fullString length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop){
        [attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:result.range];
        
        [self.label setAttributedText:attributedText];

    }];

2014년 4월 11일 금요일

iOS 7에서 UITextView RETURN 시에 다음라인이 다 보이지 않고 라인과 캐럿이 걸쳐 보이는 현상

ios7에서 UITextView에 텍스트 입력시에 Return키를 입력하면 다음줄이 보이지 않고 프레임 밖으로 가려서 보이지 않는 현상


UITextViewDelegate 하수를 다음과 같이 작성.

- (void)textViewDidChangeSelection:(UITextView *)textView
{
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        if ([textView.text characterAtIndex:textView.text.length-1] != ' ') {
            textView.text = [textView.text stringByAppendingString:@" "];
        }
        
        NSRange range0 = textView.selectedRange;
        NSRange range = range0;
        if (range0.location == textView.text.length) {
            range = NSMakeRange(range0.location - 1, range0.length);
        } else if (range0.length > 0 &&
                   range0.location + range0.length == textView.text.length) {
            range = NSMakeRange(range0.location, range0.length - 1);
        }
        if (!NSEqualRanges(range, range0)) {
            textView.selectedRange = range;
        }
    }

}