美文网首页demo兴趣iOSiOS Developer
UIAlertView文字居左,UILabel内边距设置

UIAlertView文字居左,UILabel内边距设置

作者: 未来可期me | 来源:发表于2017-06-29 14:52 被阅读576次

    最近在项目中,需要有个强制更新功能,更新内容,动态显示,系统的content设置,内容是居中,丑爆了!!所以自定义个UILabel,因为需要有内边距!

    UILabel不像UIButton那样,有个contentEdgeInsets、titleEdgeInsets、imageEdgeInsets供我们设置文字或图片与按钮边界的界限,所以我们只能另外想其他办法来实现。其实,办法也很简单,只需要我们自定义UILabel,然后重写drawTextInRect:方法即可实现我们的目标。

    如下图

    UIAlertView文字居左,UILabel内边距设置
     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"发现新版本"
                                                                       message:nil
                                                                      delegate:self
                                                             cancelButtonTitle:nil
                                                             otherButtonTitles:@"立即更新", nil];
                        alert.tag = 3;
                        DGLabel *textLabel = [[DGLabel alloc] init];
                        textLabel.font = [UIFont systemFontOfSize:13];
                        textLabel.numberOfLines =0;
                        textLabel.textAlignment =NSTextAlignmentLeft;
                        textLabel.textInsets = UIEdgeInsetsMake(0.f, 10.f, 0.f, 10.f); // 设置左内边距
                        textLabel.text = responseObject[@"content"];
                        [alert setValue:textLabel forKey:@"accessoryView"];
                        [alert show];
    
    

    DGLabel.h

    #import <UIKit/UIKit.h>
    
    @interface DGLabel : UILabel
    
    @property (nonatomic, assign) UIEdgeInsets textInsets; // 控制字体与控件边界的间隙
    
    @end
    

    DGLabel.m

    #import "DGLabel.h"
    
    @implementation DGLabel
    
    - (instancetype)init {
        if (self = [super init]) {
            _textInsets = UIEdgeInsetsZero;
        }
        return self;
    }
    
    - (instancetype)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            _textInsets = UIEdgeInsetsZero;
        }
        return self;
    }
    
    - (void)drawTextInRect:(CGRect)rect {
        [super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
    }
    
    @end
    
    

    相关文章

      网友评论

        本文标题:UIAlertView文字居左,UILabel内边距设置

        本文链接:https://www.haomeiwen.com/subject/ubbmcxtx.html