一般在iOS上的文字是不會有什麼變化的,若要設置大小,顏色或更多設定,基本上都是跟著實體去做設定。
比如說
UILabel* myLabel =[[UILabel alloc] init];
//設定文字大小
[myLabel setFont:[UIFont systemFontOfSize:18]];
//設定文字顏色
[myLabel setTextColor:[UIColor redColor]];
這樣的設定會套用在所有的文字內容,如:我的文字
若要在單一實體上套用不同的文字設置,則需要套用NSAttributedString。
//設置多屬性文字
[myLabel setAttributedText:myAttributedText];
而通常我們會新增一個可變動的多屬性文字來做多重處理
//新增一個可變動的多屬性文字
NSMutableAttributedSting* myMutableAttributedString = [[NSMutableAttributedString alloc] initWithString:@"原價$100元"];
設定屬性時,需要取得要設定的範圍以及要什麼樣的屬性
// 設定文字範圍及屬性
NSRange range1 = NSMakeRange(0, 2);
NSDictionary* attributeDic1 = @{NSForegroundColorAttributeName:[UIColor grayColor],
NSFontAttributeName:[UIFont systemFontOfSize:14]};
[myMutableAttributedString setAttributes: attributeDic1 range: range1];
NSRange range2 = NSMakeRange(2, 1);
NSDictionary* attributeDic2 = @{NSForegroundColorAttributeName:[UIColor lightGrayColor],
NSFontAttributeName:[UIFont systemFontOfSize:16]};
[myMutableAttributedString setAttributes: attributeDic2 range: range2];
NSRange range3 = NSMakeRange(3, 3);
NSDictionary* attributeDic3 = @{NSForegroundColorAttributeName:[UIColor lightGrayColor],
NSFontAttributeName:[UIFont systemFontOfSize:16],
NSStrikethroughStyleAttribuedName:@"1"};
[myMutableAttributedString setAttributes: attributeDic3 range: range3];
NSRange range4 = NSMakeRange(6, 1);
NSDictionary* attributeDic4 = @{NSForegroundColorAttributeName:[UIColor lightGrayColor],
NSFontAttributeName:[UIFont systemFontOfSize:16]};
[myMutableAttributedString setAttributes: attributeDic4 range: range4];
輸出的結果則為:原價$100元
要注意的是,若設置了多屬性文字後,原本設定在實體上的文字屬性都會被覆蓋掉喔。
可以進到NSAttributedString.h查看有什麼屬性可以設定,基本上想得到的通通都有。