首页 > 学院 > 开发设计 > 正文

iOS开发之UILabel

2019-11-14 20:31:00
字体:
来源:转载
供稿:网友

UILabel是iOS开发中常用的一个组件,主要用来显示内容。

UILabel的主要使用如下:

	/*尺寸*/	CGRect labelRect = CGRectMake(100, 100, 80, 40);	/*初始化*/	UILabel *titleLabel = [[UILabel alloc] initWithFrame:labelRect];	/*一些属性的设置*/	titleLabel.font = [UIFont systemFontOfSize:16.0f];	titleLabel.textColor = [UIColor blueColor];	titleLabel.text = @"标题";	/*将UILabel添加到视图上*/	[self.view addSubview:titleLabel];

以上是UILabel的一些基本属性,另外还有一些文字位置等属性可以设置。具体的信息可以参看iOS Developer Library中关于UILabel的定义。

利用UILabel展示动态内容

使用UILabel展示静态的内容是一件很简单的事情。但是有些时候,我们需要从后台获取数据,然后再由UILabel展示,这个时候,UILabel的内容并不是固定的,如果我们给出一个静态的尺寸,很可能就会造成显示上的问题。这种情况下,我们可以借助其他的一些手段来处理。下面是处理的代码:

- (void)resizeLabelByContent:(UILabel *)label{   	CGSize maxSize = CGSizeMake(label.width, 999);   	label.numberOfLines = 0;    	NSString *contentStr = label.text;    	UIFont *contentFont = label.font;        	CGRect contentFrame;        	NSString *version = [[UIDevice currentDevice] systemVersion];    	if ([version floatValue] < 7.0) {        	CGSize contentStringSize = [contentStr sizeWithFont:contentFont 				constrainedToSize:maxSize lineBreakMode:label.lineBreakMode];        	contentFrame = CGRectMake(label.left, label.top, label.width, 				contentStringSize.height);    	} else {        	NSDictionary *contentDic = [NSDictionary 				dictionaryWithObjectsAndKeys:contentFont, NSFontAttributeName, nil];        	CGSize contentStrSize = [contentStr boundingRectWithSize:maxSize 				options:NSStringDrawingUsesLineFragmentOrigin attributes:contentDic 				context:nil].size;        	contentFrame = CGRectMake(label.left, label.top, label.width, 			contentStrSize.height);    	}    	label.frame = contentFrame;}

当UILabel用来展示动态内容的时候,直接调用即可。

[titleLabel resizeLabelByContent];

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表