Frame, Bounds는 CGRect 타입인 View의 Instance Property이다.
둘의 차이점에 대해 알아보자.

 

 

 

CGRect

- 사각형의 위치와 크기를 포함하는 구조체

- CGPoint - x, y 좌표, CGSize - width, height

 

 

 

Frame

The frame rectangle, which describes the view's location and size in its superview's coordinate system.

  • 상위뷰의 좌표 시스템
  • frame을 변경하면?
    자식 뷰의 위치도 변경된다 -> 자식 뷰의 frame은 변경되지 않았으므로
  • 언제 사용?
    UIView 위치나 크기를 설정하는 경우

Bounds

The bounds rectange, which describes the view's location and size in its own coordinate system.

  • 자신만의 좌표 시스템
  • 기본 좌표: (0, 0)
  • bounds의 origin을 변경한다는 것은?  곧, subView들이 화면상에서 drawing 되는 위치가 변경됨을 의미

    => subView들의 frame 값을 변화시키는 것이 아니다. 부모뷰 좌표축이 변하면서 subView가 그려져야 하는 위치가 달라졌기 때문
    ScrollView/TableView 등을 스크롤할 때, scrollView.bounds가 변하고, 그리하여 subView들이 그려지는 위치가 대표적인 예
    (subView들의 frame이 달라지는 게 아님)

    ex ) targetView.bounds.origin.x = 60; 
           targetView.bounds.origin.y = 50; 
           이라고 하면 targetView가 x축-> 60, y축-> 50으로 이동된 자식 뷰가 그려짐.!!!!!!!!!! 
  • 언제 사용?
    - View 내부에 그림을 그릴 때 (drawRect)
    - transformation 후, View의 크기를 알고 싶을 때
    - 하위 View를 정렬하는 것과 같이 내부적으로 변경하는 경우

 

 

 

Ref.

Frame과 bound의 차이(2/2) : https://zeddios.tistory.com/231

Frame과 bound의 차이(1/2) : https://zeddios.tistory.com/203

CGRect와 CGSize의 차이, 그리고 CGPoint: https://zeddios.tistory.com/201

'iOS > iOS 기본기' 카테고리의 다른 글

[iOS] Delegate, Notification, KVO 비교 및 장단점 정리  (0) 2019.12.10
[iOS] Layout - Safe Area  (0) 2019.12.09
[iOS] int vs NSInteger vs NSNumber  (0) 2019.12.05
[iOS] NSOperation vs. GCD  (0) 2019.11.29
[iOS] UIKit framework 계층도  (1) 2019.11.25

특히 UIView 클래스 계층 중요!

 

 

UIViewController를 category하여 ViewController를 제거하는 메소드를 추가해서 사용하고 있다.


아래에 따라 뷰 컨트롤러를 제거하는 로직이 다르므로 체크하여 분기를 태워야겠다.

  • Navigation Stack에 Push된 뷰 컨트롤러인가
  • 모달 형식으로 Present된 뷰 컨트롤러인가


아래 코드는 현재 뷰가 모달 형식인지 아닌지를 체크하는 로직이다.


- (BOOL)isModal

{

    if([self presentingViewController])

        return YES;

    if([[[self navigationController] presentingViewController] presentedViewController] == [self navigationController])

        return YES;

    if([[[self tabBarController] presentingViewController] isKindOfClass:[UITabBarController class]])

        return YES;

    

    return NO;

}



모달 형식이면 

[self dismissViewControllerAnimated:YES completion:nil];


네비게이션 스택에 푸시된 형식이면

[self.navigationController popViewControllerAnimated:YES];





Ref.

http://stackoverflow.com/questions/23620276/check-if-view-controller-is-presented-modally-or-pushed-on-a-navigation-stack

현재 디바이스에 설치된 앱이 App Store에 출시된 최신 버전인지 체크하는 방법이다.


+ (BOOL)needsUpdate

{

    NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];

    NSString* appID = infoDictionary[@"CFBundleIdentifier"];

    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?bundleId=%@", appID]];

    NSData* data = [NSData dataWithContentsOfURL:url];

    NSDictionary* lookup = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    

    BOOL result = NO;

    

    if ([lookup[@"resultCount"] integerValue] == 1){

        NSString* appStoreVersion = lookup[@"results"][0][@"version"];

        NSString* currentVersion = infoDictionary[@"CFBundleShortVersionString"];


        NSArray *versionArray = [currentVersion componentsSeparatedByString:@"."];

        NSArray *appStoreArray = [appStoreVersion componentsSeparatedByString:@"."];

        

        for (int i=0; i<appStoreArray.count; i++) {

            

            int bundleStat = [versionArray[i] intValue];

            int serverStat = [appStoreArray[i] intValue];

            

            if (bundleStat == serverStat) {

                result = NO;

                continue;

                

            } else if (bundleStat > serverStat) {

                result = NO;

                break;

                

            } else {

                result = YES;

                break;

            }

        }

    }

    

    return result;

}


참고로 lookup 변수에는 앱스토어 등록되어있는 나의 앱에 대한 여러 정보들을 갖고있더라.







Search와 관련된 3 APIs

  • NSUserActivity
  • Web Markup
  • CoreSpotlight => 이 중에서 Core Spotlight를 자세히 볼 것이다.

Core Spotlight API 사용하기

  • Core Spotlight에 엔트리 저장하기

1. iOS 9에서 사용 가능한 Search API 사용하여 Core Spotlight에 저장이 가능하다.
아래에서 보듯이, 각각의 CSSearchableItem을 만들고 searchableItems라는 임시 어레이에 저장하자.

let attributeSet = CSSearchableItemAttributeSet(itemContentType: "image" as String)
attributeSet.title = person.name
attributeSet.contentDescription = "This is an entry all about the interesting person called \(person.name)"
attributeSet.thumbnailData = UIImagePNGRepresentation(person.image)

let item = CSSearchableItem(uniqueIdentifier: person.id, domainIdentifier: "com.ios9daybyday.SearchAPIs.people", attributeSet: attributeSet)
searchableItems.append(item)

2. CSSearchableIndex에서 indexSearchableItems를 호출하자.
이것은 실제로 사용자들이 검색할 수 있고 그 결과를 볼 수 있도록 CoreSpotlight에 저장하는 것이다.

CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems, completionHandler: 
{ error -> Void in
    if error != nil {
        print(error?.localizedDescription)
} })

3. 다음과 같이 검색 결과를 Core Spotlight에서 볼 수 있다.


  • 사용자에 대한 응답
    spotlight에서 검색 결과를 선택하면, AppDelegate의 continueUserActivity UIAppicationDelegate로 들어오게 된다. 이 곳에 로직을 추가하면 된다. 

func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {

    // Find the ID from the user info
    let friendID = userActivity.userInfo?["kCSSearchableItemActivityIdentifier"] as ! String

    // Find the root table view controller and make it show the friend with this ID
    let navigationController = (window?.rootViewController as! UINavigationController)
    navigationController.popToRootViewControllerAnimagted(false)
    let friendTableViewController = navigationController.viewController.first as! FriendTableViewController
    friendTableViewController.showFriend(friendID)

    return true

  }


더 많은 정보



소스코드 - https://github.com/shinobicontrols/iOS9-day-by-day/tree/master/01-Search-APIs
참고 - iOS 9 Day by Day - by shinobicontrols



NSString Documentation

SWIFT

func componentsSeparatedByString(_ separatorString) -> [String]

OBJECTIVE-C

- (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator


Example

// token으로 문자열 자르기
NSString *list = @"1;2;3;4;5";
NSArray *listItems = [list componentsSeparatedByString:@";"];

// 결과값
// {@"1", @"2", @"3", @"4", @"5"}


+ Recent posts