Objective-C
开发过程中,一般需要用到弹出框提醒用户,使用系统自带的AlertController最方便快捷,但有时候往往需要自定义其中的某些样式。如图:
我们可以通过递归的方式找到alertview然后进行自定义
//递归找到title
UIView *messageParentView = [self getParentViewOfTitleAndMessageFromView:alert.view];
if (messageParentView && messageParentView.subviews.count > 1) {
DLog(@"%@",messageParentView.subviews);
}
- (UIView *)getParentViewOfTitleAndMessageFromView:(UIView *)view {
for (UIView *subView in view.subviews) {
if ([subView isKindOfClass:[UILabel class]]) {
return view;
}else{
UIView *resultV = [self getParentViewOfTitleAndMessageFromView:subView];
if (resultV) return resultV;
}
}
return nil;
}
通过打印的subviews
[
<UILabel: 0x7f90987d2e90; frame = (0 0; 0 0); text = '1、订单交易完成后雨露才会进入账户(线上交易为快递...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x608000482a80>>,
<UILabel: 0x7f90987b1d00; frame = (0 0; 0 0); text = ''; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x608000095090>>,
<UIView: 0x7f90987cd8d0; frame = (0 0; 0 0); clipsToBounds = YES; layer = <CALayer: 0x60800043c3e0>>,
<UIView: 0x7f90987e4500; frame = (0 0; 0 0); clipsToBounds = YES; layer = <CALayer: 0x60800043efe0>>
]
找到前2个Label分别是title和message。
文章终于有人看了看到评论有疑问补个swift版的
swift
道理都是通的
if let view = self.getParentViewOfTitleAndMessageFromView(view: alertC.view) {
print(view.subviews)
}
func getParentViewOfTitleAndMessageFromView(view:UIView) -> UIView? {
for item in view.subviews {
if item.isKind(of: UILabel.self) {//如果subview包含label直接返回
return view
}else{//继续遍历 找到包含label的view
if let resultView = self.getParentViewOfTitleAndMessageFromView(view: item) {
return resultView
}
}
}
return nil
}
通过打印的subviews
[<UILabel: 0x15fe11e00; frame = (0 0; 0 0); text = '标题'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x1c4091800>>,
<UILabel: 0x15fe12480; frame = (0 0; 0 0); text = '内容'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x1c4092f70>>,
<UIView: 0x15fe10690; frame = (0 0; 0 0); clipsToBounds = YES; layer = <CALayer: 0x1c422ac20>>,
<UIView: 0x15fe12de0; frame = (0 0; 0 0); clipsToBounds = YES; layer = <CALayer: 0x1c422a060>>]
找到前2个Label分别是title和message。