在兩個UIView
實例之間找到最低共同祖先的最有效方式是什麼?兩個視圖之間的共享祖先
由於缺少實施Lowest Common Ancestor,有沒有任何UIKit
API可以用來找到它?
NSView
有ancestorSharedWithView:
所以我懷疑這可能會比iOS更早。
我目前使用的這種快速和骯髒的解決方案,這是低效的,如果給定的觀點是沒有兄弟姐妹或直接祖先。
- (UIView*)lyt_ancestorSharedWithView:(UIView*)aView
{
if (aView == nil) return nil;
if (self == aView) return self;
if (self == aView.superview) return self;
UIView *ancestor = [self.superview lyt_ancestorSharedWithView:aView];
if (ancestor) return ancestor;
return [self lyt_ancestorSharedWithView:aView.superview];
}
(對於那些實施了類似的方法,將Lyt項目的單元測試可能會有所幫助)
你唯一的選擇就是走了'superview'環比上升到頂部,然後找到其中兩個發散。我不知道任何API(除了'superview'),這將有所幫助。 – rmaddy
我不瞭解API,但我不會全力以赴;而是以交替的方式上升,爲每個我找到的UIView保留一個計數器,並在每次訪問它時增加1。將其計數器設置爲2的第一個UIView是最低的共同祖先。例如,您可以使用散列圖將視圖映射到其計數器。這是我能想到的最簡單的事情,並不難實現。 –