- (void)sizeToFit 方法遇到的问题

view调用 - (void)sizeToFit 方法前,view的frame不能是用 - (void)sizeToFit 方法得到的。

例如;

-(void)btnClick{

NSMutableAttributedString*attributedString1 = [[NSMutableAttributedString alloc] initWithString:desc attributes: attributeDict];

[attributedString1 beginEditing];

//把行间距模型加入NSMutableAttributedString模型

[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, desc.length)];

[attributedString1 addAttribute:NSKernAttributeName value:@(1.8)range:NSMakeRange(0, desc.length)];

[attributedString1 endEditing];

[_descLabel setAttributedText:attributedString1];

[_descLabel sizeToFit];

}

当我不停的点击这个按钮的时候,你会发现 _descLabel 的文本位置会发生变化。

解决方案:

在重复调用的方法中,先设置一次 label 的 frame,再调用 - (void)sizeToFit 方法。如下面的黑色字体: 

-(void)btnClick{

[_descLabel setFrame:CGRectMake(15,70,CGRectGetWidth(_whiteView.frame) -15-15,1)];

NSMutableAttributedString*attributedString1 = [[NSMutableAttributedString alloc] initWithString:desc attributes: attributeDict];

[attributedString1 beginEditing];

//把行间距模型加入NSMutableAttributedString模型

[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, desc.length)];

[attributedString1 addAttribute:NSKernAttributeName value:@(1.8)range:NSMakeRange(0, desc.length)];

[attributedString1 endEditing];

[_descLabel setAttributedText:attributedString1];

[_descLabel sizeToFit];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容