前言:
有的需求會(huì)給出文字豎排的方式,下面給出兩種思路來實(shí)現(xiàn)這種效果.一是為UILabel添加分類,添加一個(gè)文字豎排的屬性;而是為NSString添加分類,添加一個(gè)文字豎排的方法- (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];