zl程序教程

您现在的位置是:首页 >  其它

当前栏目

固定UILabel宽度分行显示

显示 固定 宽度 UILabel
2023-09-14 08:57:17 时间

固定UILabel宽度分行显示

这种小伎俩估计都被用烂了,笔者给大家提供一个category文件,供大家简单设置哦.

各种富文本效果哦(普通文本也是可以用的呢):

3行,固定宽度200

2行,固定宽度200

无限行,固定宽度250

无限行,固定宽度250,设置段落样式

源码:

UILabel+SizeToFit.h  与  UILabel+SizeToFit.m

//

// UILabel+SizeToFit.h

// SizeToFit

// Copyright (c) 2014年 Y.X. All rights reserved.

#import UIKit/UIKit.h 

@interface UILabel (SizeToFit)

- (void)fixWidth:(CGFloat)width // 固定宽度

 position:(CGPoint)position // 文字起始位置

 numberOfLines:(NSInteger)lines // 行数(如果为0则表示为无限行)

 lineBreakMode:(NSLineBreakMode)mode; // 文字断开方式

@end


//

// UILabel+SizeToFit.m

// SizeToFit

// Copyright (c) 2014年 Y.X. All rights reserved.

#import "UILabel+SizeToFit.h"

@implementation UILabel (SizeToFit)

- (void)fixWidth:(CGFloat)width

 position:(CGPoint)position

 numberOfLines:(NSInteger)lines

 lineBreakMode:(NSLineBreakMode)mode

 CGRect newRect = self.frame;

 newRect.size.width = width;

 newRect.origin = position;

 self.frame = newRect;

 self.numberOfLines = lines;

 self.lineBreakMode = mode;

 [self sizeToFit];

@end

使用的源码(注,此处用到了自己写的一些源码,请君自行替换):
//

// RootViewController.m

// SizeToFit

// Copyright (c) 2014年 Y.X. All rights reserved.

#import "RootViewController.h"

#import "UILabel+SizeToFit.h"

#import "FontPool.h"

@interface RootViewController ()

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

 if (self) {

 return self;

- (void)viewDidLoad

 [super viewDidLoad];

 self.view.backgroundColor = [UIColor blackColor];

 // 注册字体

 REGISTER_FONT(bundleFont(@"新蒂小丸子体.ttf"), @"新蒂小丸子体");

 // 设置段落样式

 NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];

 style.firstLineHeadIndent = 14.f * 2;

 // 设置富文本

 NSString *testStr = @"如果我有尾巴的话 —— 说起来有点不好意思,只要和你在一起,一定会止不住摇起来的吧。";

 NSArray *array \

 = @[[ConfigAttributedString font:[UIFont fontWithName:CUSTOM_FONT(@"新蒂小丸子体", 0) size:12.f]

 range:[testStr range]],

 [ConfigAttributedString foregroundColor:[UIColor whiteColor]

 range:[testStr range]],

 [ConfigAttributedString paragraphStyle:style

 range:[testStr range]],

 [ConfigAttributedString font:[UIFont fontWithName:CUSTOM_FONT(@"新蒂小丸子体", 0) size:14.f]

 range:[@"如果我有尾巴的话" rangeFrom:testStr]],

 [ConfigAttributedString foregroundColor:[UIColor redColor]

 range:[@"如果我有尾巴的话" rangeFrom:testStr]]];



核心代码处:

注意,只有执行了sizeToFit才是解决问题的关键所在:

就是这么简单:)


纵向排列文字以及禁止文字选中 内容包括demo代码,应用和定义,以及参考文献,本文主要内容是本人学习过程中遇到css的零碎知识点1(就是以前自己不知道的),我都记下来了,需要的朋友可以过来参考下,喜欢的可以点个赞,希望对大家有所帮助。 writing-mode: tb-rl; (纵向排列文字)应用: 说明:设置或检索对象的内容块固有的书写方向。西方语言一般都是 lr-tb 的书写方式,但是亚洲语言 lr-tb | tb-rl 的书写方式都有。作为IE的私有属性之一,IE5.5率先实现了 writing-mode ,后期被w3c采纳成标准属性;此属性效果不能被累加使用。例如,父对象的此属性值