ios 計算label寬度(高度)出錯在iPhone5s、iphone6上出錯,iphone5siphone6

來源:互聯網
上載者:User

ios 計算label寬度(高度)出錯在iPhone5s、iphone6上出錯,iphone5siphone6

今天使用Label的時候,需要計算UILabel的高度,發現在4,4s上顯示正常,在iPhone5s、iphone6上顯示出錯

使用的方法為:

NSString *teacherComment = @"評語是寫給學生看的,所以一方面評語要使用學生能看得懂的英語來寫,所使用的詞彙和文法不能過高或過低於學生的現有水平,要切合學生的實際水平,符合學生的個性心理...";        float commentHeight = 0.0;    if ([teacherComment isEqual:@""]||teacherComment==nil||[[NSNull null] isEqual:teacherComment]) {        commentHeight = BASIC_LABEL_HEIGHT;    }else{        CGSize commentRect = [teacherComment sizeWithFont:[UIFont fontWithName:TITLE_FONT size:FONT_SIZE_FOURTEEN] constrainedToSize:CGSizeMake(180, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];                if (commentRect.height > BASIC_LABEL_HEIGHT) {            commentHeight = commentRect.height;        }        else        {            commentHeight = BASIC_LABEL_HEIGHT;        }    }

這段代碼在iPhone4或iPhone4s上顯示正常,系統分別是ios7,ios8的系統。但是在iphone5s與iphone6的真機上運行後發現少了顯示不正常,有些誤差。

這個問題很奇怪了,在此記錄,上網搜尋一下,使用一下方法即可:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;        NSDictionary *attributes = @{NSFontAttributeName:[UIFont fontWithName:TITLE_FONT size:FONT_SIZE_FOURTEEN], NSParagraphStyleAttributeName:paragraphStyle.copy};                CGSize labelSize = [teacherCommentLabel.text boundingRectWithSize:CGSizeMake(180.0f, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;        labelSize.height = ceil(labelSize.height);        labelSize.width = ceil(labelSize.width);                if (labelSize.height > BASIC_LABEL_HEIGHT) {            commentHeight = labelSize.height;        }        else        {            commentHeight = BASIC_LABEL_HEIGHT;        }

使用的時候還需要判斷系統版本,所以需要注意一下,如果是ios7則使用該方法,ios6則使用上面的一個方法。

誤差:


如果您有什麼好的方法,請留言告知,謝謝。。。


延伸閱讀:www.wahenzan.com

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.