iOS开发中如何保证子视图层级(子视图顺序)
2020-08-28 本文已影响0人
抹不掉那伤1
在iOS软件开发的时候如果遇到子视图较多,逻辑较为复杂的时候很所的时候会出现需要展示出来的视图被别的视图盖住了,尤其是后接手的开发人员对如果对程序没有一个整体的把握很容易会出现问题。这里分享一个小技巧来帮助大家,也希望大家能指出我的不足,来使我有所成长。
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;
- (void)addSubview:(UIView *)view;
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;
- (void)bringSubviewToFront:(UIView *)view;
- (void)sendSubviewToBack:(UIView *)view;
这几个方法为UIView管理子视图的方法。我们可以创建个UIView的子类然后重写这些方法来达到我们让子视图显示在前面还是后面的目的。
那么又引出另外一个问题我们怎么在重写的这些方法里知道哪个应该显示在前面哪个应该显示在后面呢?
我们可以视图的指定等级,等级高的显示在前面低的显示在后面
/// 被父视图爱的等级
NS_ASSUME_NONNULL_BEGIN
/// 被父亲爱的等级
typedef NS_ENUM(NSInteger, FavoredLevel) {
FavoredLevel_Favored = 1000, /// 最爱
FavoredLevel_Like = 750,
FavoredLevel_Defout = 500, ///默认
FavoredLevel_Detest = 0 /// 厌弃
};
@interface UIView (LiveBgViewSuppot)
@property (assign, nonatomic) FavoredLevel viewFavoredLeve;
@end
NS_ASSUME_NONNULL_END
static const void *LiveBgViewSuppotProName = &LiveBgViewSuppotProName;
@implementation UIView (LiveBgViewSuppot)
- (FavoredLevel)viewFavoredLeve {
NSNumber * val = (id)objc_getAssociatedObject(self, LiveBgViewSuppotProName);
if (val) {
return val.integerValue;
} else {
return FavoredLevel_Defout;
}
}
- (void)setViewFavoredLeve:(FavoredLevel)viewFavoredLeve {
objc_setAssociatedObject(self, LiveBgViewSuppotProName, [NSNumber numberWithInteger:viewFavoredLeve], OBJC_ASSOCIATION_RETAIN);
}
@end
有了这个级别我们就能知道程序猿主观意图想把视图显示在前面还是后面了。
上面管理子视图的方法就可以重写了,由于本人算法功底薄,所以只是贴出几个表达下思路。
@interface StrictControlChildrenView : UIImageView
@end
@implementation StrictControlChildrenView
- (void)addSubview:(UIView *)view
{
[super addSubview:view];
for (UIView * subview in [self.subviews reverseObjectEnumerator]) {
if (view == subview) {
continue;
}
if (subview.viewFavoredLeve > view.viewFavoredLeve) {
[self insertSubview:view belowSubview:subview];
} else if (subview.viewFavoredLeve <= view.viewFavoredLeve) {
break;
}
}
}
- (void)bringSubviewToFront:(UIView *)view
{
[super bringSubviewToFront:view];
for (UIView * subview in [self.subviews reverseObjectEnumerator]) {
if (view == subview) {
continue;
}
if (subview.viewFavoredLeve > view.viewFavoredLeve) {
[self insertSubview:view belowSubview:subview];
} else if (subview.viewFavoredLeve <= view.viewFavoredLeve) {
break;
}
}
}
- (void)sendSubviewToBack:(UIView *)view
{
[super sendSubviewToBack:view];
for (UIView * subview in self.subviews) {
if (view == subview) {
continue;
}
if (subview.viewFavoredLeve > view.viewFavoredLeve) {
[self insertSubview:view aboveSubview:subview];
} else if (subview.viewFavoredLeve <= view.viewFavoredLeve) {
break;
}
}
}
@end