前言:
有的需求会给出文字竖排的方式,下面给出两种思路来实现这种效果.一是为UILabel添加分类,添加一个文字竖排的属性;而是为NSString添加分类,添加一个文字竖排的方法- (NSString *)VerticalString
方法一(UILabel添加分类):
#import <UIKit/UIKit.h>
@interface UILabel (Extension)
@property (nonatomic) NSString *verticalText;
@end
#import "UILabel+Extension.h"
#import "objc/Runtime.h"
@implementation UILabel (Extension)
- (NSString *)verticalText{
// 利用runtime添加属性
return objc_getAssociatedObject(self, @selector(verticalText));
}
- (void)setVerticalText:(NSString *)verticalText{
objc_setAssociatedObject(self, &verticalText, verticalText, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
NSMutableString *str = [[NSMutableString alloc] initWithString:verticalText];
NSInteger count = str.length;
for (int i = 1; i < count; i ++) {
[str insertString:@"\n" atIndex:i*2-1];
}
self.text = str;
self.numberOfLines = 0;
}
@end
具体用法如下:
NSString *string = @"北冥有鱼,其名为鲲。";
UILabel *label = [[UILabel alloc] initWithFrame:(CGRectMake(self.view.bounds.size.width * 0.5, 100, 300, 600))];
label.textColor = [UIColor redColor];
label.verticalText = string;
[label sizeToFit];//顶部显示
[self.view addSubview:label];
方法二(为NSSring添加分类):
#import <Foundation/Foundation.h>
@interface NSString (Extension)
- (NSString *)VerticalString;
@end
#import "NSString+Extension.h"
@implementation NSString (Extension)
- (NSString *)VerticalString{
NSMutableString * str = [[NSMutableString alloc] initWithString:self];
NSInteger count = str.length;
for (int i = 1; i < count; i ++) {
[str insertString:@"\n" atIndex:i*2 - 1];
}
return str;
}
@end
具体用法如下:
NSString *verText = [@"北冥有鱼,其名为鲲。" VerticalString];
UILabel *label = [[UILabel alloc] initWithFrame:(CGRectMake(self.view.bounds.size.width * 0.5, 100, 300, 600))];
label.text = verText;
label.numberOfLines = 0;
label.textColor = [UIColor redColor];
[label sizeToFit];//顶部显示
[self.view addSubview:label];