sizeToFit运行异常 [英] sizeToFit is functioning oddly

查看:43
本文介绍了sizeToFit运行异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,每次发生后端数据库更改时都会执行.本质上,我在父视图中有一个标签.标签会通过许多状态消息之一进行更新,每条状态消息均在另一行中以新行(\ n)结尾.每条状态消息仅需在一行上,而不能越过.

I have a segment of code that gets executed everytime a backend database change occurs. Essentially I have a label inside of a parent view. The label gets updated by one of many status messages each one on a different line ended by a new line (\n). Each status message needs to be on one line only and not go over.

我遇到的问题是,在第一次重新加载View时,一切正常.但是,当我在屏幕上并且背景发生变化时,状态消息会偶尔显示在多行上.虽然sizeToFit在使标签与包含父视图的视图一样高的方面做得很好,但在宽度方面却做得很差.就是说,它将使多行文本分开,而不是仅查看换行符.

The problem I am having is that everything works fine when the View first reloads. However when I am on the screen and a change occurs in background, once in a while a status message displays on multiple lines. While sizeToFit does a great job of making the label as high as the parent containing view, it does so poorly in terms of width. That is it will break up text on multiple lines as opposed to looking at the line breaks only.

我该怎么办?

self.messageLabel.text = message; //lets get the status message.
        [self.messageLabel sizeToFit];
        [self.messageLabel setNeedsDisplay];
        CGRect frame = [self.messageView frame];
        frame.size.height = self.messageLabel.bounds.size.height;
        self.messageView.frame = frame;
        self.messageLabel.center = CGPointMake(CGRectGetMidX(self.messageView.bounds), CGRectGetMidY(self.messageView.bounds)-(self.messageView.cornerRadius/4));
        self.messageLabel.backgroundColor = [UIColor orangeColor];
        [self.messageView setNeedsDisplay];

推荐答案

为了确定标签的大小,您需要研究NSString size方法.其中有许多可以告诉您字符串的大小,字体和各种限制.

In order to determine the size that your label will need to be, you need to look into the NSString size methods. There's a number of them that can tell you the size a string will be given a font, and various constraints.

例如,[@"string" sizeWithFont: forWidth: lineBreakMode:];将返回一个CGSize,您可以使用该CGSize来适当调整标签的大小.

For example [@"string" sizeWithFont: forWidth: lineBreakMode:]; will return a CGSize that you can then use to size your label appropriately.

顺便说一句,我发现UILabel不能很好地处理多行字符串.您最好编写自己的UIView子视图,该子视图可以处理多行文本,每行都有自己的标签.

As an aside, I find the UILabel does not handle strings with multiple lines well. You may be better off writing your own subview of UIView that can handle multiple lines of text, each with its own label.

这篇关于sizeToFit运行异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆