您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 獲取 UIView 完整層級結構的方法

編輯:iOS 開發綜合

在 iOS 中獲取 UIView 的所有層級結構

應用場景

在實際 iOS 開發中,我們往往需要知道某個 UI 控件包含哪些子控件,並理清它們的層級結構、各自的 frame 與 bounds,以便完成複雜的 UI 佈局。下面的代碼能方便地獲取某個 UI 控件的完整層級結構,我們可以將結果寫入本地磁盤並導出為 XML 文件,這樣就能很直觀地查看其內部細節。

 /** * 返回傳入veiw的所有層級結構 * * @param view 需要獲取層級結構的view * * @return 字符串 */ - (NSString *)digView:(UIView *)view { if ([view isKindOfClass:[UITableViewCell class]]) return @""; // 1.初始化 NSMutableString *xml = [NSMutableString string]; // 2.標簽開頭 [xml appendFormat:@"<%@ frame=\"%@\"", view.class, NSStringFromCGRect(view.frame)]; if (!CGPointEqualToPoint(view.bounds.origin, CGPointZero)) { [xml appendFormat:@" bounds=\"%@\"", NSStringFromCGRect(view.bounds)]; } if ([view isKindOfClass:[UIScrollView class]]) { UIScrollView *scroll = (UIScrollView *)view; if (!UIEdgeInsetsEqualToEdgeInsets(UIEdgeInsetsZero, scroll.contentInset)) { [xml appendFormat:@" contentInset=\"%@\"", NSStringFromUIEdgeInsets(scroll.contentInset)]; } } // 3.判斷是否要結束 if (view.subviews.count == 0) { [xml appendString:@" />"]; return xml; } else { [xml appendString:@">"]; } // 4.遍歷所有的子控件 for (UIView *child in view.subviews) { NSString *childXml = [self digView:child]; [xml appendString:childXml]; } // 5.標簽結尾 [xml appendFormat:@"", view.class]; return xml; }
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved