ios - UILabel Padding 基于内容

标签 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 只是“-”时宽度没有减少?

最佳答案

这令人困惑。在 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。为什么?

关于ios - UILabel Padding 基于内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12946036/

相关文章:

ios - 我如何从 xib 创建自定义 uiview

ios - 使用 AutoLayout 获取 UILabel 宽度很热门吗?

ios - 为 MBProgressHUD 添加完成回调

ios - 如何创建一个像 UILabel 一样具有 intrinsicContentSize 的 View ?

swift - 字体 Luciest-Guy 未在 UILabel 中垂直居中

ios - frame.size.width 和 frame.width 的区别

ios - 将 UIView 拉伸(stretch)到 UIScrollView 宽度

swift - 如何使用 CGRect 从右侧定位这些 UIView 元素

ios - UIWebView全屏播放HTML5视频,触摸不再被识别

ios - 如何用字典中的数据填充 UITableView。 swift