IOS 動態擷取 UILabel 元素的寬度和高度

來源:互聯網
上載者:User

標籤:


//高度自適應UIFont *font = [UIFont fontWithName:@"Arial" size:13];//設定一個行高上限CGSize size = CGSizeMake(320,1000);//計算實際frame大小,並將label的frame變成實際大小CGSize labelsize = [entity.content sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];DebugLog(@"height = %f", height) ;
方法一:CGSize titleSize = [titleContent boundingRectWithSize:CGSizeMake(kScreen_Width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;或方法二:CGSize labelsize = [str sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];//擷取單行字串的寬度和高度NSString *content = @"擷取 UILabel 寬度和高度測試";CGSize size =[content sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}];//擷取多行字串的寬度和高度UILabel *titleLabel = [[UILabel alloc]init];    titleLabel.font = [UIFont systemFontOfSize:1];    NSString *titleContent = @"擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試";    titleLabel.text = titleContent;    titleLabel.numberOfLines = 0;//多行顯示,計算高度    titleLabel.textColor = [UIColor lightGrayColor];    CGSize titleSize = [titleContent boundingRectWithSize:CGSizeMake(kScreen_Width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;    titleLabel.size = titleSize;    titleLabel.x = 0;    titleLabel.y = 0;    [self.view addSubview:titleLabel];    //或者//初始化labelUILabel *label = [[UILabel alloc] init];//設定自動行數與字元換行[label setNumberOfLines:0];[label.lineBreakMode:UILineBreakModeWordWrap]; // 測試字串NSString *str = @"擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試擷取 UILabel 寬度和高度測試";UIFont *font = [UIFont fontWithName:@"Arial" size:13];//設定一個行高上限CGSize size = CGSizeMake(320,1000);//計算實際frame大小,並將label的frame變成實際大小CGSize labelsize = [str sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];[label setFrame:CGRectMake:(0,0, labelsize.width, labelsize.height)];







IOS 動態擷取 UILabel 元素的寬度和高度

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.