给你两个 UIView
或者其子类的对象 viewA
和 viewB
.
如果它们同属一个父view
的话, 请找到并返回这个父 view, 否则请返回nil
.
- (UIView *) findCommonSuperViewBetween: (UIView *)viewA and: (UIView *)viewB { }
大家先写,一会儿贴下我写的答案。
贴下我的代码:
- (UIView *) findCommonSuperViewBetween: (UIView *)viewA and: (UIView *)viewB { if (viewA == nil || viewB == nil) return nil; UIView *tempA = viewA; UIView *tempB = viewB; while (tempA != tempB) { tempA = tempA == nil? viewB: [tempA superview]; tempB = tempB == nil? viewA: [tempB superview]; } return tempA; }
1 xieguobihaha 2016-11-27 17:15:32 +08:00 我的思路是将 viewA 和 viewB 的所有父 view 分别放入两个数组,数组数量少的那个说明位于视图上层,取它的第一个父视图即可,代码如下 https://gist.github.com/hiXgb/6cf33f97fa2439a44d23be3e4691b16e |
2 starqoq 2016-11-27 17:29:19 +08:00 via Android 求 lca ? |
3 xieguobihaha 2016-11-27 17:30:18 +08:00 |
5 nagato OP @xieguobihaha 说实话有点惨不忍睹,面试应该是挂的 |
6 xieguobihaha 2016-11-27 17:39:43 +08:00 @nagato 求指教 |
7 kimown 2016-11-27 17:41:30 +08:00 via Android 题目真没看懂, uiview ,这是前端? |
8 xieguobihaha 2016-11-27 17:51:47 +08:00 @nagato 我自己发现一个错误了, while 循环里最后跳出条件得改一下,不然死循环了。 |
9 nagato OP @xieguobihaha 且不说你做的是不是正确。单从你的代码就能看出你的编码能力还挺一般的. 比如你想把所有的 superview 全加数组里,为啥可以写出这么多代码和变量,不是两个 while loop 就好了吗 不过我挺喜欢你的态度 |
10 nagato OP |
![]() | 12 binux 2016-11-27 18:06:45 +08:00 via Android 多重继承怎么办 |
![]() | 15 fengyunSmlie 2016-11-27 18:14:51 +08:00 菜鸟前来膜拜大佬 |
16 a412739861 2016-11-27 18:14:52 +08:00 贴个现成的吧。源代码在 Masonry 中,查看 View+MASAdditions.h/m 文件即可。 这是个实例方法,类方法也一样;只是 self 变成 view1 罢了。 遍历 self 的 superview ,去匹配 view 。 然后取 view 得 superview ,再遍历一遍 self 的 superview 。循环不到,也就返回 nil 了。 记得回复不能 markdown 的样子,就直接复制下代码,不会太好看。 - (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view { MAS_VIEW *closestCommOnSuperview= nil; MAS_VIEW *secOndViewSuperview= view; while (!closestCommonSuperview && secondViewSuperview) { MAS_VIEW *firstViewSuperview = self; while (!closestCommonSuperview && firstViewSuperview) { if (secOndViewSuperview== firstViewSuperview) { closestCommOnSuperview= secondViewSuperview; } firstViewSuperview = firstViewSuperview.superview; } secOndViewSuperview= secondViewSuperview.superview; } return closestCommonSuperview; } |
17 xieguobihaha 2016-11-27 18:38:50 +08:00 @nagato  |
18 nagato OP @xieguobihaha 你再仔细看看 |
![]() | 21 Biscuits 2016-12-01 02:25:38 +08:00 可以 hitTest 试试吧。 |