Dynamic支持CollectionView布局 、 MotionEffects特效 、 BlurImage效果 、 TextKit
2015-12-15 20:54
453 查看
1 使用UIDynamicAnimator对集合视图进行布局
1.1 问题
UIKit Dynamic动力模型一个非常有趣的用途就是影响集合视图的布局,可以给集合视图的布局添加各种动力行为,使其产生丰富多彩的效果,本案例使用UIDynamicAnimator对集合视图进行布局,实现一个弹性列表,如图-1所示:图-1
1.2 方案
首先创建一个SingleViewApplication项目,给UIColor类创建一个分类UIColor+RandomColor,提供一个产生随机颜色的静态方法randomColor。其次创建一个自定义布局类TRCollectionViewSpringCellLayout继承至UICollectionViewFlowLayout,该类有一个UIDynamicAnimator类型的属性animator。重写prepareLayout方法(该方法在布局开始前自动调用),在该方法中使用initWithCollectionViewLayout:创建animator对象,然后给每个items都添加UIAttachmentBehavior行为。
然后实现layoutAttributesForElementsInRect: 和 layoutAttributesForItemAtIndexPath: 这两个方法,程序运行的时候会通过调用它们来询问 collectionView每一个 item 的布局信息。
再实现shouldInvalidateLayoutForBoundsChange:,该方法会在集合视图的 bounds发生改变的时候被调用,根据最新的contentOffset 调整animator中behaviors 的参数,在重新调整之后该方法返回NO。
最后在TRViewController的viewDidLoad方法中使用TRCollectionViewSpringCellLayout对象创建集合视图collectionView,并且实现集合视图的协议方法给集合视图加载数据。
1.3 步骤
实现此案例需要按照如下步骤进行。步骤一:创建UIColor分类
首先创建一个SingleViewApplication项目,给UIColor类创建一个分类UIColor+RandomColor,提供一个产生随机颜色的静态方法randomColor,代码如下所示:
+ (UIColor *)randomColor
{
CGFloat red = arc4random() % 256 / 256.0;
CGFloat green = arc4random() % 256 / 256.0;
CGFloat blue = arc4random() % 256 / 256.0;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}
步骤二:创建自定义布局类TRCollectionViewSpringCellLayout
首先创建一个自定义布局类TRCollectionViewSpringCellLayout继承至UICollectionViewFlowLayout,该类有一个UIDynamicAnimator类型的属性animator,代码如下所示:
@interface TRCollectionViewSpringCellLayout ()
@property (strong, nonatomic) UIDynamicAnimator *animator;
@end
其次重写prepareLayout方法(该方法在布局开始前自动调用),在该方法中使用initWithCollectionViewLayout:创建animator对象,然后给每个items都添加UIAttachmentBehavior行为,代码如下所示:
//布局前的准备,布局开始前自动调用
- (void)prepareLayout
{
if(!self.animator){
//通过集合视图布局创建animator对象
self.animator = [[UIDynamicAnimator alloc]initWithCollectionViewLayout:self];
CGSize contentSize = self.collectionViewContentSize;
//获取所有的items
NSArray *items = [super layoutAttributesForElementsInRect:CGRectMake(0, 0, contentSize.width, contentSize.height)];
//给每个一Cell创建UIAttachmentBehavior
for (UICollectionViewLayoutAttributes *attributes in items) {
UIAttachmentBehavior *spring = [[UIAttachmentBehavior alloc]initWithItem:attributes attachedToAnchor:attributes.center];
spring.damping = 0.6;
spring.frequency = 0.8;
[self.animator addBehavior:spring];
}
}
}
然后实现layoutAttributesForElementsInRect: 和 layoutAttributesForItemAtIndexPath: 这两个方法,程序运行的时候会通过调用它们来询问 collectionView每一个 item 的布局信息,代码如下所示:
//在集合视图滚动时会自动调用,返回所有cell的属性,并传递可见的矩形区域
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
//当collectionView需要layout信息时由animator提供
return [self.animator itemsInRect:rect];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
return [self.animator layoutAttributesForCellAtIndexPath:indexPath];
}
最后实现shouldInvalidateLayoutForBoundsChange:,该方法会在集合视图的 bounds发生改变的时候被调用,根据最新的contentOffset 调整animator中behaviors 的参数,在重新调整之后该方法返回NO,代码如下所示:
//当bounds发生变化时,调用方法,为不同的Cell改变不同的锚点
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
UIScrollView *scrollView = self.collectionView;
//获取滚动的距离
CGFloat scrollDelta = newBounds.origin.y - scrollView.bounds.origin.y;
//手指所在的位置
CGPoint touchLocation = [scrollView.panGestureRecognizer locationInView:scrollView];
//计算和改动每一个Cell的锚点
for (UIAttachmentBehavior *spring in self.animator.behaviors) {
UICollectionViewLayoutAttributes *item = [spring.items firstObject];
CGPoint center = item.center;
CGPoint anchorPoint = spring.anchorPoint;
CGFloat distance = fabsf(touchLocation.y - anchorPoint.y);
CGFloat scrollResistance = distance / 600;
center.y += (scrollDelta>0)?MIN(scrollDelta, scrollDelta * scrollResistance):MAX(scrollDelta, scrollDelta * scrollResistance);
item.center = center;
//当item处于动画中时,如果对象主动修改了位置信息,需要更新动画
[self.animator updateItemUsingCurrentState:item];
}
return NO;
}
步骤四:遵守委托协议,实现协议方法
首先在TRViewController的viewDidLoad方法中创建TRCollectionViewSpringCellLayout对象layout,并设置相关属性,代码如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
TRCollectionViewSpringCellLayout *layout = [[TRCollectionViewSpringCellLayout alloc]init];
layout.itemSize = CGSizeMake(300, 40);
layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
}
然后通过layout创建collectionView,并注册Cell,代码如下所示:
static NSString *cellIdentifier = @"MyCell";
- (void)viewDidLoad
{
[super viewDidLoad];
TRCollectionViewSpringCellLayout *layout = [[TRCollectionViewSpringCellLayout alloc]init];
layout.itemSize = CGSizeMake(300, 40);
layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
collectionView.showsVerticalScrollIndicator = NO;
collectionView.showsHorizontalScrollIndicator = NO;
collectionView.dataSource = self;
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
[self.view addSubview:collectionView];
}
最后实现集合视图的协议方法给集合视图加载数据,代码如下所示:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 50;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor randomColor];
return cell;
}
1.4 完整代码
本案例中,TRViewController.m文件中的完整代码如下所示:#import "TRViewController.h"
#import "TRCollectionViewSpringCellLayout.h"
#import "UIColor+RandomColor.h"
@implementation TRViewController
static NSString *cellIdentifier = @"MyCell";
- (void)viewDidLoad
{
[super viewDidLoad];
TRCollectionViewSpringCellLayout *layout = [[TRCollectionViewSpringCellLayout alloc]init];
layout.itemSize = CGSizeMake(300, 40);
layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
collectionView.showsVerticalScrollIndicator = NO;
collectionView.showsHorizontalScrollIndicator = NO;
collectionView.dataSource = self;
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
[self.view addSubview:collectionView];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 50;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor randomColor];
return cell;
}
@end
本案例中,TRCollectionViewSpringCellLayout.m文件中的完整代码如下所示:
#import "TRCollectionViewSpringCellLayout.h"
@interface TRCollectionViewSpringCellLayout ()
@property (strong, nonatomic) UIDynamicAnimator *animator;
@end
@implementation TRCollectionViewSpringCellLayout
//布局前的准备,布局开始前自动调用
- (void)prepareLayout
{
//给每个一Cell创建UIAttachmentBehavior
if(!self.animator){
//通过集合视图布局创建animator对象
self.animator = [[UIDynamicAnimator alloc]initWithCollectionViewLayout:self];
CGSize contentSize = self.collectionViewContentSize;
//获取所有的items
NSArray *items = [super layoutAttributesForElementsInRect:CGRectMake(0, 0, contentSize.width, contentSize.height)];
for (UICollectionViewLayoutAttributes *attributes in items) {
UIAttachmentBehavior *spring = [[UIAttachmentBehavior alloc]initWithItem:attributes attachedToAnchor:attributes.center];
spring.damping = 0.6;
spring.frequency = 0.8;
[self.animator addBehavior:spring];
}
}
}
//在集合视图滚动时会自动调用,返回所有cell的属性,并传递可见的矩形区域
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
//当collectionView需要layout信息时由animator提供
return [self.animator itemsInRect:rect];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
return [self.animator layoutAttributesForCellAtIndexPath:indexPath];
}
//当bounds发生变化时,调用方法,为不同的Cell改变不同的锚点
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
UIScrollView *scrollView = self.collectionView;
//获取滚动的距离
CGFloat scrollDelta = newBounds.origin.y - scrollView.bounds.origin.y;
//手指所在的位置
CGPoint touchLocation = [scrollView.panGestureRecognizer locationInView:scrollView];
//计算和改动每一个Cell的锚点
for (UIAttachmentBehavior *spring in self.animator.behaviors) {
UICollectionViewLayoutAttributes *item = [spring.items firstObject];
CGPoint center = item.center;
CGPoint anchorPoint = spring.anchorPoint;
CGFloat distance = fabsf(touchLocation.y - anchorPoint.y);
CGFloat scrollResistance = distance / 600;
center.y += (scrollDelta>0)?MIN(scrollDelta, scrollDelta * scrollResistance):MAX(scrollDelta, scrollDelta * scrollResistance);
item.center = center;
//当item处于动画中时,如果对象主动修改了位置信息, 需要更新动画
[self.animator updateItemUsingCurrentState:item];
}
return NO;
}
@end
本案例中,UIColor+RandomColor.h文件中的完整代码如下所示:
#import <UIKit/UIKit.h>
@interface UIColor (RandomColor)
+ (UIColor *)randomColor;
@end
本案例中,UIColor+RandomColor.m文件中的完整代码如下所示:
#import "UIColor+RandomColor.h"
@implementation UIColor (RandomColor)
+ (UIColor *)randomColor
{
CGFloat red = arc4random() % 256 / 256.0;
CGFloat green = arc4random() % 256 / 256.0;
CGFloat blue = arc4random() % 256 / 256.0;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}
@end
2 给视图添加MotionEffect特效
2.1 问题
UIMotionEffect是iOS7中新增加一个类,它能帮助开发者为用户界面加上运动拟真效果,本案例使用UIMotionEffect给视图添加MotionEffect特效,如图-2所示:图-2
2.2 方案
首先在Storyboard中搭建界面,在View中拖放一个ImageView控件作为backgroundView,在右边栏的检查器中设置好ImageView的显示图片。然后再拖放一个View控件覆盖在ImageView上面作为foregroundView,大小比ImageView略小,View控件里面是一个TextView控件,给TextView控件添加一些显示内容。其次将ImageView控件和View关联成ViewController的属性backgroundView和foregroundView。
然后在viewDidLoad方法中给backgroundView和foregroundView添加MotionEffect效果。
最后需要在真机里面运行才能看到backgroundView和foregroundView根据设备的移动而产生偏移。
2.3 步骤
实现此案例需要按照如下步骤进行。步骤一:搭建Storyboard界面
首先在Storyboard中搭建界面,在View中拖放一个和View同等大小的ImageView控件作为backgroundView,这里需要注意为了保证视图偏移的时候不会有空白,所以ImageView的大小要设置的比屏幕大,这里ImageView的frame设置为-100,-100,520,760。
然后在右边栏的检查器中设置好ImageView的显示图片。然后再拖放一个View控件覆盖在ImageView上面作为foregroundView,大小比ImageView略小,View控件里面是一个TextView控件,给TextView控件添加一些显示内容,Storyboard界面效果如图-3所示:
图-3
步骤二:创建添加MotionEffect效果
首先将ImageView控件和View关联成ViewController的属性backgroundView和foregroundView,代码如下所示:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *backgroundView;
@property (weak, nonatomic) IBOutlet UIView *foregroundView;
@end
然后在viewDidLoad方法中给backgroundView和foregroundView添加MotionEffect效果,代码如下所示:
- (void)viewDidLoad {
[super viewDidLoad];
self.foregroundView.layer.cornerRadius = 6.0f;
self.foregroundView.layer.masksToBounds = YES;
//给foregroundView添加MotionEffect
UIInterpolatingMotionEffect *xAxis = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
//设置x轴的最大和最小偏移值
xAxis.minimumRelativeValue = @(-15.0);
xAxis.maximumRelativeValue = @(15.0);
UIInterpolatingMotionEffect *yAxis = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
yAxis.minimumRelativeValue = @(-15.0);
yAxis.maximumRelativeValue = @(15.0);
//创建UIMotionEffectGroup对象
UIMotionEffectGroup *foregroundMotionEffect = [[UIMotionEffectGroup alloc] init];
foregroundMotionEffect.motionEffects = @[xAxis, yAxis];
//添加MotionEffect
[self.foregroundView addMotionEffect:foregroundMotionEffect];
//给backgroundView添加MotionEffect
UIInterpolatingMotionEffect *xAxis2 = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
//设置y轴的最大和最小偏移值
xAxis2.minimumRelativeValue = @(25.0);
xAxis2.maximumRelativeValue = @(-25.0);
UIInterpolatingMotionEffect *yAxis2 = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
yAxis2.minimumRelativeValue = @(32.0);
yAxis2.maximumRelativeValue = @(-32.0);
UIMotionEffectGroup *backgroundMotionEffect = [[UIMotionEffectGroup alloc] init];
backgroundMotionEffect.motionEffects = @[xAxis2, yAxis2];
[self.backgroundView addMotionEffect:backgroundMotionEffect];
}
步骤三:真机上运行程序
由于MotionEffect是根据设备的运动而产生的,所以需要在真机里面运行才能看到backgroundView和foregroundView根据设备的移动而产生偏移,真机上运行效果如图-4、图-5、图-6、图-7所示:
图-4
图-5
图-6
图-7
2.4 完整代码
本案例中,ViewController.m文件中的完整代码如下所示:#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *backgroundView;
@property (weak, nonatomic) IBOutlet UIView *foregroundView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.foregroundView.layer.cornerRadius = 6.0f;
self.foregroundView.layer.masksToBounds = YES;
//给foregroundView添加MotionEffect
UIInterpolatingMotionEffect *xAxis = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
//设置最大和最小偏移值
xAxis.minimumRelativeValue = @(-15.0);
xAxis.maximumRelativeValue = @(15.0);
UIInterpolatingMotionEffect *yAxis = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
yAxis.minimumRelativeValue = @(-15.0);
yAxis.maximumRelativeValue = @(15.0);
UIMotionEffectGroup *foregroundMotionEffect = [[UIMotionEffectGroup alloc] init];
foregroundMotionEffect.motionEffects = @[xAxis, yAxis];
[self.foregroundView addMotionEffect:foregroundMotionEffect];
//给backgroundView添加MotionEffect
UIInterpolatingMotionEffect *xAxis2 = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
xAxis2.minimumRelativeValue = @(25.0);
xAxis2.maximumRelativeValue = @(-25.0);
UIInterpolatingMotionEffect *yAxis2 = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
yAxis2.minimumRelativeValue = @(32.0);
yAxis2.maximumRelativeValue = @(-32.0);
UIMotionEffectGroup *backgroundMotionEffect = [[UIMotionEffectGroup alloc] init];
backgroundMotionEffect.motionEffects = @[xAxis2, yAxis2];
[self.backgroundView addMotionEffect:backgroundMotionEffect];
}
@end
3 给图片添加模糊效果
3.1 问题
IOS7在视觉方面有许多改变,其中非常吸引人的功能之一就是在整个系统中巧妙的使用了模糊效果,本案例使用UIImage+ImageBlur分类给图片添加各种模糊效果,如图-8所示:图-8
3.2 方案
首先在Storyboard中搭建界面,场景中拖放一个ImageView控件和五个Button控件,在右边栏设置好ImageView的显示图片,然后分别将Button的tag设置为0、1、2、3、4,别分代表不同的图片模糊效果。其次将ImageView关联成ViewController的属性imageView,将五个Button关联同一个方法changeEffect:。
然后导入UIImage+ImageBlur文件,该分类提供的几种图片模糊效果的方法。
最后实现changeEffect:方法,该方法根据用户的选择,通过image的图片模糊方法实现不同的图片的模糊效果。
3.3 步骤
实现此案例需要按照如下步骤进行。步骤一:搭建Stroyboard界面
首先在Storyboard中搭建界面,场景中拖放一个ImageView控件和五个Button控件,在右边栏设置好ImageView的显示图片,然后分别将Button的tag设置为0、1、2、3、4,别分代表不同的图片模糊效果,搭建好的界面如图-9所示:
图-9
然后将ImageView关联成ViewController的属性imageView,将五个Button关联同一个方法changeEffect:,代码如下所示:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
步骤二:实现图片模糊效果
首先导入UIImage+ImageBlur文件,该分类提供的几种图片模糊效果的方法。
然后实现changeEffect:方法,该方法根据用户的选择,通过image的图片模糊方法实现不同的图片的模糊效果,代码如下所示:
- (IBAction)changeEffect:(UIButton *)sender {
UIImage *effectImage;
switch (sender.tag) {
case 0:
effectImage = [self.imageView.image applyLightEffect];
break;
case 1:
effectImage = [self.imageView.image applyExtraLightEffect];
break;
case 2:
effectImage = [self.imageView.image applyDarkEffect];
break;
case 3:
effectImage = [self.imageView.image applyTintEffectWithColor:[UIColor lightGrayColor]];
break;
case 4:
effectImage = [UIImage imageNamed:@"xiaoqingxin07.jpg"];
break;
}
self.imageView.image = effectImage;
}
运行程序可以看到LightEffect、ExtraLightEffect、DarkEffect、TintEffectWithColor等图片模糊效果分别如图-10、图-11、图-12及图-13所示:
图-10
图-11
图-12
图-13
3.4 完整代码
本案例中,ViewController.m文件中的完整代码如下所示:#import "ViewController.h"
#import "UIImage+ImageEffects.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
- (IBAction)changeEffect:(UIButton *)sender {
UIImage *effectImage;
switch (sender.tag) {
case 0:
effectImage = [self.imageView.image applyLightEffect];
break;
case 1:
effectImage = [self.imageView.image applyExtraLightEffect];
break;
case 2:
effectImage = [self.imageView.image applyDarkEffect];
break;
case 3:
effectImage = [self.imageView.image applyTintEffectWithColor:[UIColor lightGrayColor]];
break;
case 4:
effectImage = [UIImage imageNamed:@"xiaoqingxin07.jpg"];
break;
}
self.imageView.image = effectImage;
}
@end
4 演示属性字符串的用法
4.1 问题
NSAtrributeString属性字符串是基于TextKit来构建的字符串对象,将字符串和样式信息组合在一起。本案例演示属性字符串的用法,如图-14所示:图-14
4.2 方案
首先在viewDidLoad方法中创建一个NSDictionary类型的对象attributes,以键值对的方式管理字符串的样式信息。其次创建一个NSAttributedString类型的字符串attrString,使用initWithString:attributes:方法进行初始化,string参数是字符串的内容,attributes参数就是上一步创建的attributes对象,即字符串的样式信息。
然后再创建一个NSMutableAttributedString类型的字符串mAttrString,与NSAttributedString类型不同的是NSMutableAttributedString类型是可变的属性字符串。
可以使用addAttribute:value:range:方法,或者addAttributes:range:方法给mAttrString添加样式,两个方法的区别就是前者只能添加一个键值对表示的样式,后者可以添加多个键值对表示的样式。
最后将mAttrString设置为self.label.attributedText属性,即可在界面看见带有属性样式的字符串。
4.3 步骤
实现此案例需要按照如下步骤进行。步骤一:搭建Storyboard界面
首先Storyboard的场景中拖放一个Label控件,并将Label控件关联成TRViewController的属性label,代码如下所示:
@interface TRViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
步骤二:创建属性字符串
首先在viewDidLoad方法中创建一个NSDictionary类型的对象attributes,以键值对的方式管理字符串的样式信息,NSForegroundColorAttributeName是key表示前景色即字符串的颜色,对应的value是一个UIColor类型的对象。NSFontAttributeName也是key表示字体名称,对应的value是一个UIFont类型的对象,代码如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:26]};
}
其次创建一个NSAttributedString类型的字符串attrString,使用initWithString:attributes:方法进行初始化,string参数是字符串的内容,attributes参数就是上一步创建的attributes对象,即字符串的样式信息,代码如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:26]};
NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:@"Hello World." attributes:attributes];
}
然后再创建一个NSMutableAttributedString类型的字符串mAttrString,与NSAttributedString类型不同的是NSMutableAttributedString类型是可变的属性字符串,代码如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:26]};
NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:@"Hello World." attributes:attributes];
NSMutableAttributedString *mAttrString = [attrString mutableCopy];
}
再使用addAttribute:value:range:方法,或者addAttributes:range:方法给mAttrString添加样式,两个方法的区别就是前者只能添加一个键值对表示的样式,后者可以添加多个键值对表示的样式,代码如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:26]};
NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:@"Hello World." attributes:attributes];
NSMutableAttributedString *mAttrString = [attrString mutableCopy];
[mAttrString addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:35] range:NSMakeRange(3, 2)];
[mAttrString addAttributes:@{NSBackgroundColorAttributeName : [UIColor lightGrayColor], NSTextEffectAttributeName : NSTextEffectLetterpressStyle} range:NSMakeRange(6, 3)];
}
最后将mAttrString设置为self.label.attributedText属性,即可在界面看见带有属性样式的字符串,代码如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:26]};
NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:@"Hello World." attributes:attributes];
NSMutableAttributedString *mAttrString = [attrString mutableCopy];
[mAttrString addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:35] range:NSMakeRange(3, 2)];
[mAttrString addAttributes:@{NSBackgroundColorAttributeName : [UIColor lightGrayColor], NSTextEffectAttributeName : NSTextEffectLetterpressStyle} range:NSMakeRange(6, 3)];
self.label.attributedText = mAttrString;
}
4.4 完整代码
本案例中,TRViewController.m文件中的完整代码如下所示:#import "TRViewController.h"
@interface TRViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
@implementation TRViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:26]};
NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:@"Hello World." attributes:attributes];
NSMutableAttributedString *mAttrString = [attrString mutableCopy];
[mAttrString addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:35] range:NSMakeRange(3, 2)];
[mAttrString addAttributes:@{NSBackgroundColorAttributeName : [UIColor lightGrayColor], NSTextEffectAttributeName : NSTextEffectLetterpressStyle} range:NSMakeRange(6, 3)];
self.label.attributedText = mAttrString;
}
@end
相关文章推荐
- 锋利的JQuery —— JQuery性能优化
- Mousetrap - Keyboard shortcuts in Javascript
- DOM 对象控制 HTML
- jQuery扩展与noConflict
- jQuery官网API的简易解读
- Hibernate抓取--fetching
- JSON.stringify 语法实例讲解
- UVa 106 - Fermat vs Pythagoras(数论题目)
- 谈谈react-router学习
- jquery validate
- [Servlet&JSP] 封装器的使用
- [caffe]大体介绍
- javascript性能
- js打印window.print()图片打印
- 单引号、双引号在javascript、HTML中的转义字符
- 手机横屏竖屏css
- myeclipse中导入的jquery文件报错
- 《JavaScript DOM编程艺术》学习整理
- html基础语法
- AngularJS 学习路线