NSAttributeString顾名思义,就是可以携带各种属性的字符穿,提供了一种管理字符串中单个字符属性(字体,颜色,下划线等等)属性的方式。
继承自NSObject,所以其不具有UIKit的特性。
首先看下目标效果图
然后
第一步 设计接口(这是一个很好的习惯,由接口驱动编程)
创建一个UIView的子类DrawStringView
然后,这个类的接口有两个
1 显示的String内容
2 初始化的方法
这样,DrawStringView.h的完整代码如下
- #import <UIKit/UIKit.h>
-
- @interface DrawStringView : UIView
- @property (strong,nonatomic)NSString * contentString;
- -(id)initWithContent:(NSString *)content Frame:(CGRect)frame;
- @end
第二步 完成实现
具体的过程见代码注释
这样,完整代码如下
- </pre><pre name="code" class="objc">
-
-
-
-
-
-
-
- #import "DrawStringView.h"
-
- @implementation DrawStringView
-
- #pragma mark - property
-
- -(void)setContentString:(NSString *)contentString{
- _contentString = contentString;
- [self setNeedsDisplay];
- }
- #pragma mark - redraw
- -(void)drawRect:(CGRect)rect{
- NSMutableParagraphStyle * style = [[NSMutableParagraphStyle alloc] init];
- style.alignment = NSTextAlignmentCenter;
- style.lineBreakMode = NSLineBreakByWordWrapping;
- UIFont * font = [UIFont fontWithName:@"Helvetica" size:30];
- NSMutableAttributedString * attributeStirng = [[NSMutableAttributedString alloc]initWithString:self.contentString];
- NSDictionary * firstPartAttributes = @{ NSFontAttributeName:font,
- NSParagraphStyleAttributeName:style,
- NSForegroundColorAttributeName:[UIColor whiteColor],
- NSStrokeColorAttributeName:[UIColor blueColor],
- NSStrokeWidthAttributeName:@(3)
- };
- NSDictionary * secondPartAttributes = @{ NSFontAttributeName:font,
- NSParagraphStyleAttributeName:style,
- NSForegroundColorAttributeName:[UIColor whiteColor],
- NSStrokeColorAttributeName:[UIColor redColor],
- NSStrokeWidthAttributeName:@(3)
- };
- NSUInteger halfLocation = (int)attributeStirng.length/2;
- [attributeStirng addAttributes:firstPartAttributes range:NSMakeRange(0,halfLocation)];
- [attributeStirng addAttributes:secondPartAttributes range:NSMakeRange(halfLocation,attributeStirng.length - halfLocation)];
- [attributeStirng drawInRect:self.bounds];
- }
- #pragma mark - init method
- -(id)initWithContent:(NSString *)content Frame:(CGRect)frame{
- if (self = [super initWithFrame:frame]) {
- self.contentString = content;
- self.opaque = NO;
- }
- return self;
- }
- @end
当然,NSAttributeString还有更多的属性,以上是常用的几种,更多的属性参照XCode中的文档,很详细
三 使用这个类
- UIView * viewWithString = [[DrawStringView alloc] initWithContent:@"This is test string" Frame:CGRectMake(100, 100, 200, 200)];
- [self.view addSubview:viewWithString];