IOS-55-UILable文字两边对齐的实现方式
2016-03-01 12:38
656 查看
Apple并没有给出两边对齐模式的设置,需要自己写两个方法:
- (void)viewDidLoad { [super viewDidLoad]; UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 380, 160, 21)]; label2.backgroundColor = [UIColor greenColor]; [self conversionCharacterInterval:7 current:@"今天天气" withLabel:label2]; [self.view addSubview:label2]; } /** * 设置UILable里的文字两边对齐 * maxInteger : 应占字符数 (中文为1,英文为0.5/个) * currentString : 要显示的文字 */ - (void)conversionCharacterInterval:(NSInteger)maxInteger current:(NSString *)currentString withLabel:(UILabel *)label { CGRect rect = [[currentString substringToIndex:1] boundingRectWithSize:CGSizeMake(200,label.frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: label.font} context:nil]; NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:currentString]; float strLength = [self getLengthOfString:currentString]; [attrString addAttribute:NSKernAttributeName value:@(((maxInteger - strLength) * rect.size.width)/(strLength - 1)) range:NSMakeRange(0, strLength)]; label.attributedText = attrString; } - (float)getLengthOfString:(NSString*)str { float strLength = 0; char *p = (char *)[str cStringUsingEncoding:NSUnicodeStringEncoding]; for (NSInteger i = 0 ; i < [str lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++) { if (*p) { strLength++; } p++; } return strLength/2; }
相关文章推荐
- .Net Telerik Web UI 安装和使用入门
- 关于requirejs和grunt压缩合并是否矛盾
- UITabbar相关
- DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
- mssql-异常value '0000-00-00' can not be represented as java.sql.Date
- Windows Vista下UIPI和Windows消息的故事
- 让一个正方形View以四个角中的任意一角为起点放大或缩小
- UITabBarController
- JAVA学习之GUI组件中Toolkit的使用
- 1085. Perfect Sequence (25)
- 一起学习extjs(四)alias,config,mixins,require用法
- pyquery小记
- pyquery小记
- iOS开发之使用Storyboard预览UI在不同屏幕上的运行效果
- Build.VERSION.SDK_INT
- Qt使用教程之创建Qt Quick UI表单(四)
- SystemUI新增快捷方式
- 在iOS 8中使用UIAlertController
- 根据范围给UILabel设置颜色或字体,行间距
- 放肆地用 UIBezierPath 和 CAShapeLayer 画各种图形