iOS 自定义属性 attribute

本文展示了如何在iOS中自定义属性来设置按钮的文字,包括字体、颜色和对齐方式。通过创建NSMutableAttributedString,分别设置不同部分的字体大小和颜色,然后将属性字符串应用到UIButton的标题中,最后调整按钮的内边距和文字对齐方式,以实现理想的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 //注册协议

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"我已阅读并同意《YESOUL条款》"];

    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14.0] range:NSMakeRange(0, 7)];

    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"d20037"] range:NSMakeRange(7, 10)];

    

    UIButton *agree = [[UIButton alloc] initWithFrame:CGRectMake(1010 100, 30)];

    [agree setAttributedTitle:attributedString forState:UIControlStateNormal];

    agree.titleLabel.textColor = [UIColor colorWithHexString:@"ffffff"];

    agree.backgroundColor=[UIColor clearColor];

//按钮文字左对齐,设置距左边多少像素

    agree.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

    agree.titleEdgeInsets = UIEdgeInsetsMake(0, 1, 0, 0);

    agree.titleLabel.textAlignment = NSTextAlignmentLeft;

    agree.titleLabel.font = [UIFont systemFontOfSize:15];

    [self.view addSubview:agree];


 //如图所示:

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值