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];

  • 相关阅读:
    hdu_5791_Two(DP)
    hdu_5783_Divide the Sequence(贪心)
    hdu_5769_Substring(后缀数组)
    hdu_5778_abs(暴力)
    hdu_5776_sum(前缀和维护)
    hdu_5777_domino(贪心)
    [wikioi2069]油画(贪心)
    [bzoj 1503][NOI 2004]郁闷的出纳员(平衡树)
    数据结构练习
    [poj3274]排排站(Hash)
  • 原文地址:https://www.cnblogs.com/nanoCramer/p/3069789.html
Copyright © 2011-2022 走看看