UILabel Padding基于内容

时间:2012-10-18 02:03:21

标签: ios uilabel cgrect cg

我有使用填充填充的问题。我想让我的uilabel只有一个字符显示填充事件

http://i.stack.imgur.com/T4Aet.png

所以我填写了“提问”字样,

我所做的是:

#import "NetraCell.h"
#import <QuartzCore/QuartzCore.h>
@implementation NetraCell
@synthesize NetraLabelForPrice,NetraImageDeals;


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        /////implement for NetraLabelForPrice
//
         NetraLabelForPrice=[[UILabel alloc] init];
         NetraLabelForPrice.backgroundColor=[UIColor brownColor];
         NetraLabelForPrice.textColor=[UIColor whiteColor];
         NetraLabelForPrice.textAlignment=NSTextAlignmentCenter;
         NetraLabelForPrice.font=[UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
         [NetraLabelForPrice.layer setCornerRadius:20];


    //   NetraImageDeals=[[UIImage alloc] init];
     [self.contentView addSubview:NetraLabelForPrice];
         /////


    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
- (void)layoutSubviews {

    [super layoutSubviews];
    self.imageView.frame = CGRectMake(10.0f, 15.0f, 80.0f, 80.0f);
    self.NetraLabelForPrice.frame = CGRectMake(100.0f, 15.0f, NetraLabelForPrice.frame.origin.x, 25);
    [self.imageView.layer setCornerRadius:7.0f];
    [self.NetraLabelForPrice.layer setCornerRadius:7.0f];

}
@end

我这样说

self.NetraLabelForPrice.frame = CGRectMake(100.0f, 15.0f, NetraLabelForPrice.frame.origin.x, 25);

但为什么当我label.text只是“ - ”宽度没有减少?

1 个答案:

答案 0 :(得分:1)

这令人困惑。在layoutSubviews中,您尝试将标签的新宽度设置为标签的当前x原点。这毫无意义。您应该根据标签中的文本加上您希望的填充来设置标签的宽度。

layoutSubviews中,替换此行:

self.NetraLabelForPrice.frame = CGRectMake(100.0f, 15.0f, NetraLabelForPrice.frame.origin.x, 25);

用这个:

[NetraLabelForPrice sizeToFit]; // make the label just big enough for the text
CGRect labelFrame = NetraLabelForPrice.frame;
labelFrame.origin.x = 100;
labelFrame.origin.y = 15;
labelFrame.size.width += 20; // set to the amount of padding you want
NetraLabelForPrice.frame = labelFrame;

代码中的另一个奇怪的事情 - 在init方法中,您将标签的圆角半径设置为20,然后在layoutSubviews中将其设置为7。为什么呢?