UIAlertController text alignment

前端 未结 8 1812
醉话见心
醉话见心 2020-12-05 04:07

Is there a way to change the alignment of the message displayed inside a UIAlertController on iOS 8?

I believe accessing the subviews and changing it for the UILabel

8条回答
  •  执念已碎
    2020-12-05 04:58

    Navigate to subview tree until you get to the UILabels for the title and the message

    NSArray *viewArray = [[[[[[[[[[[[alertController view] subviews] firstObject] subviews] firstObject] subviews] firstObject] subviews] firstObject] subviews] firstObject] subviews];
    UILabel *alertTitle = viewArray[0]
    UILabel *alertMessage = viewArray[1];
    alertMessage.textAlignment = NSTextAlignmentLeft;
    

    However, you may want to make an category for it

    @interface UIAlertController (ShowMeTheLabels)
    
    @property (nonatomic, strong) UILabel *titleLabel, *messageLabel;
    
    @end
    
    @implementation UIAlertController (ShowMeTheLabels)
    @dynamic titleLabel;
    @dynamic messageLabel;
    
    - (NSArray *)viewArray:(UIView *)root {
        NSLog(@"%@", root.subviews);
        static NSArray *_subviews = nil;
        _subviews = nil;
        for (UIView *v in root.subviews) {
            if (_subviews) {
                break;
            }
            if ([v isKindOfClass:[UILabel class]]) {
                _subviews = root.subviews;
                return _subviews;
            }
            [self viewArray:v];
        }
        return _subviews;
    }
    
    - (UILabel *)titleLabel {
        return [self viewArray:self.view][0];
    }
    
    - (UILabel *)messageLabel {
        return [self viewArray:self.view][1];
    }
    
    @end
    

    Then you can align the text like this

    yourAlertController.messageLabel.textAlignment = NSTextAlignmentLeft;
    

提交回复
热议问题