ios 给label添加横线

来源:互联网 发布:部落冲突九本满防数据 编辑:程序博客网 时间:2024/04/30 11:59
UILabel *labelTitle = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-100, 130, 200, 30)];
//    labelTitle.text = @"星座运势";
    labelTitle.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:labelTitle];
    //给label添加横线
    NSString *stratt = @"星座运势解析";
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:stratt];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid|NSUnderlineStyleSingle) range:NSMakeRange(0, stratt.length)];
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(0, stratt.length)];
    [labelTitle setAttributedText:attri];

@implementation UILabel (colorLab)

// 设置某段字的颜色
- (void)setColor:(UIColor *)color fromIndex:(NSInteger)location length:(NSInteger)length
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:self.text];
    [str addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(location, length)];
    self.attributedText = str;
    
}

// 设置某段字的字体
- (void)setFont:(UIFont *)font fromIndex:(NSInteger)location length:(NSInteger)length
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:self.text];
    [str addAttribute:NSFontAttributeName value:font range:NSMakeRange(location, length)];
    self.attributedText = str;
    
}

//设置行间距
-(void)setText:(NSString *)text withLineSpacing:(float)spacing
{
    NSMutableAttributedString * attributedString1 = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:spacing];
    [attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [text length])];
    [self setAttributedText:attributedString1];
    //[self sizeToFit];
}

//添加下划线
-(void)setUnderLineWithColor:(UIColor*)color
{
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:self.text];
    [attri addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, self.text.length)];
    if (color)
    {
        [attri addAttribute:NSUnderlineColorAttributeName value:color range:NSMakeRange(0, self.text.length)];
    }
    
    [self setAttributedText:attri];
}

//添加中划线
-(void)setMidLineWithColor:(UIColor*)color
{

    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:self.text];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, self.text.length)];
    if (color)
    {
        [attri addAttribute:NSStrikethroughColorAttributeName value:color range:NSMakeRange(0, self.text.length)];
    }
    
    [self setAttributedText:attri];
    
}
@end
0 0