您的位置:首页 > 其它

NSAttributedString

2016-05-26 17:15 190 查看
      要使Label上展示出如下图所示的时间,需使用 AttributedString 进行设置

      


1.创建相应类方法

#import "VoodaGetTime.h"

@implementation VoodaGetTime

+(NSAttributedString *)getAttributeSleepTimeWithMinute:(NSString *)minute

{

    int time = minute.intValue;

    NSString *strSleep = [NSString
stringWithFormat:@"%d时%d分",time/60,time
%60];

   
// 通过要显示的文字内容来创建一个带属性样式的字符串对象

    NSMutableAttributedString * result = [[NSMutableAttributedString
alloc]
initWithString:strSleep];

   
// 定义第一个文字样式字典

    NSDictionary * attributesForFirstWord =
@{NSFontAttributeName: [UIFont
boldSystemFontOfSize:20.0f],

                                              NSForegroundColorAttributeName:
RGBCOLOR(102,
126, 216)};

   
// 定义第二个文字样式字典

    NSDictionary * attributesForSecWord =
@{NSFontAttributeName: [UIFont
systemFontOfSize:11.0f],

                                            NSForegroundColorAttributeName:
RGBCOLOR(102,
126, 216)};

    

    [result setAttributes:attributesForFirstWord
range:NSMakeRange(0, strSleep.length)];

    [result setAttributes:attributesForSecWord
range:[strSleep rangeOfString:@"时"]];

    [result setAttributes:attributesForSecWord
range:[strSleep rangeOfString:@"分"]];

    return result;

}

@end

2.调用类方法

/** 获得睡眠一天的总数据 **/

    VoodaDBBleModel *sleepDayModel = [dbOperation
getSleepDayData:sleepBleModel];

    NSAttributedString *str = [[NSMutableAttributedString
alloc]
initWithString:@"0"];

    lblShallowSleepTime.attributedText = sleepDayModel.light_sleep   ? [VoodaGetTime
getAttributeSleepTimeWithMinute:sleepDayModel.light_sleep] : str;

    lblDeepSleepTime.attributedText = sleepDayModel.deep_sleep   ? [VoodaGetTime
getAttributeSleepTimeWithMinute:sleepDayModel.deep_sleep] : str;

    lblAllSleepTime.attributedText = sleepDayModel.all_time_min   ? [VoodaGetTime
getAttributeSleepTimeWithMinute:sleepDayModel.all_time_min] : str;

    NSString *hours   = sleepDayModel.all_time_min ?  [NSString
stringWithFormat:@"%d",sleepDayModel.all_time_min.intValue /
60] : @"0";

    NSString *minutes = sleepDayModel.all_time_min ?  [NSString
stringWithFormat:@"%d",sleepDayModel.all_time_min.intValue %
60] : @"0";

    float totalTime = hours.floatValue + minutes.floatValue/60;

    if (totalTime >=
8.0) {

        lblSleepLevel.text  =
@"良好";

    }else if (totalTime >=
5.0 && totalTime <
8.0){

        lblSleepLevel.text  =
@"正常";

    }else{

        lblSleepLevel.text  =
@"差";

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: