zoukankan      html  css  js  c++  java
  • 根据文字多少自动设置UILabel的宽度高度

    准备在视图中间显示一个label,宽度高度由要显示的文字决定。
    hintView = [[UIView alloc]initWithFrame:CGRectMake(10, 10, parentView.frame.size.width - 20, parentView.frame.size.height - 20)];

    hintView.backgroundColor = [UIColor grayColor];
    //设置圆角
    hintView.layer.cornerRadius = 10;
    hintView.layer.masksToBounds = YES;
    [hintView.layer setShadowOffset:CGSizeMake(2, 1)];
    [hintView.layer setShadowRadius:5];
    [hintView.layer setShadowOpacity:1];

    //set the text label
    UILabel *hintTextLabel = [[UILabel alloc] init];
    hintTextLabel.frame = CGRectMake(4, 4, hintView.frame.size.width - 8, hintView.frame.size.height - 8);
    hintTextLabel.font = [UIFont boldSystemFontOfSize:20.0f];
    hintTextLabel.backgroundColor = [UIColor clearColor];
    hintTextLabel.textColor = [UIColor blackColor];
    hintTextLabel.numberOfLines = 0; //必须定义这个属性,否则UILabel不会换行。this is used to determine how many lines this label will have.if =3,it means this label's text will show 3 lines.if =0 ,it means that this label's text will show the line whate it needs.no limit.
    hintTextLabel.textAlignment = UITextAlignmentCenter; //文本对齐方式 居中

    //根据字的多少计算label的宽度,宽度超过最大宽度后自动折行
    CGSize hintTextLabelSize = [hintText sizeWithFont:hintTextLabel.font constrainedToSize:CGSizeMake(hintTextLabel.frame.size.width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
    //根据计算结果重新设置UILabel的尺寸
    [hintTextLabel setFrame:CGRectMake(4, 4, hintTextLabelSize.width, hintTextLabelSize.height)];
    hintTextLabel.text = hintText;

    [hintView addSubview: hintTextLabel];
    [hintTextLabel release];

    //根据label的size重新计算hintView的frame大小,并且在屏幕居中显示
    hintView.frame = CGRectMake((parentView.frame.size.width - hintTextLabelSize.width) /2 , (parentView.frame.size.height - hintTextLabelSize.height) / 2, hintTextLabelSize.width + 8, hintTextLabelSize.height + 8);

    [parentView addSubview:hintView];

  • 相关阅读:
    在centos6.5上搭建elk6.5.3
    mysql 表信息查询
    pychram远程调试
    老程序员的十条告诫
    看清程序员要走的道路
    一个程序员的十年总结
    一个资深程序员成功的背后
    weisheng.cf 网站更新动态
    Endless Night 题解
    2021.1.17高一模拟赛题解
  • 原文地址:https://www.cnblogs.com/nanoCramer/p/3069789.html
Copyright © 2011-2022 走看看