외규장각 도서 환수 모금 캠페인
BLOG main image
분류 전체보기 (45)
컴퓨팅환경 (18)
프로그래밍 (18)
놀이 (2)
잡담 (7)
«   2009/07   »
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  
10,203 Visitors up to today!
Today 4 hit, Yesterday 28 hit
daisy rss
meet me at me2DAY
나눔글꼴 내려받기
tistory
'2009/07'에 해당되는 글 1건
2009/07/18 00:20

이 포스팅 제목 뽑기 참 힘들었다... 지금도 마음에 안 들지만, 그냥 할련다. 내가 원래 그렇지...

iPhone Application 개발을 하다보면 가끔 참 황당하기 짝이없는 API들을 보는 경우가 있는데, 오늘 소개할 것은 UIActionSheet와 UIAlertView다. 사실, 이 둘은 생긴 모양은 다르지만, API생김새는 거의 똑같다. 그러므로 예는 모두 UIActionSheet를 사용하겠다.

먼저, UIActionSheet를 띄워보자.

UIActionSheet *actionSheet;

actionSheet = [[UIActionSheet alloc] initWithTitle:@"뭐하실래요?"
                                          delegate:self
                                 cancelButtonTitle:@"됐어요"
                            destructiveButtonTitle:@"약주세요"
                                 otherButtonTitles:@"밥사주세요", @"술사주세요", nil];

[actionSheet showInView:[self view]];
[actionSheet release];

이제는 UIActionSheetDelegate 메소드 중 마음에 드는 것을 하나 골라 어떤 버튼이 눌렸는지 확인하여 실행에 옮길 차례다.

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == [actionSheet destructiveButtonIndex])
    {
        [self drug];
    }
    else if (buttonIndex == [actionSheet firstOtherButtonIndex])
    {
        [self dinner];
    }
    else if (buttonIndex == ([actionSheet firstOtherButtonIndex] + 1))
    {
        [self drink];
    }
}

만약, 버튼이 더 추가되거나 순서가 바뀌거나 하면... 여러 종류의 ActionSheet를 띄워야하는 ViewController라면... 생각만 해도 악몽이다. UIActionSheet의 designated initializer가 아니라 -addButtonWithTitle: 메소드를 사용하여 버튼을 추가하면서 각각의 button index를 가지고 있게 하면 그나마 낫겠지만, 그것도 그리 마음에 드는 방법은 아니다.

그래서, 별 수 없이 button title을 key로, 메소드 셀렉터를 value로 하는 dictionary를 만들어 사용해봤다.

static NSDictionary *actionSheetActions = nil;

+ (void)initialize
{
    if (!actionSheetActions)
    {
        actionSheetActions = [[NSDictionary alloc] initWithObjectsAndKeys:
                                                       @"drug",   @"약주세요",
                                                       @"dinner", @"밥사주세요",
                                                       @"drink",  @"술사주세요",
                                                       nil];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [actionSheet cancelButtonIndex])
    {
        SEL selector = NSSelectorFromString([actionSheetActions objectForKey:[actionSheet buttonTitleAtIndex:buttonIndex]]);

        if (selector)
        {
            [self performSelector:selector];
        }
    }
}

낡고 느린 방법이긴 하지만, 나는 이게 더 좋아보인다. 아... 이렇게까지 해야하는지...

PS) 이 예제에서 사용한 코드는 보기 쉽게 하기 위해 일부러 NSLocalizedString()을 사용하지 않고 한국어 타이틀을 코드에 집어넣었다.

 

이 글은 스프링노트에서 작성되었습니다.

prev"" #1 next