UILabels 未显示在 UIView 的子类中

Posted

技术标签:

【中文标题】UILabels 未显示在 UIView 的子类中【英文标题】:UILabels not showing in subclass of UIView 【发布时间】:2011-09-09 11:28:34 【问题描述】:

我有一个自定义视图(UIView 的子类),我想在其中显示一个 UIImageView 和几个 UILabel。 imageView 异步来自 FaceBook,标签从特定方法获取文本。问题是,即使 imageView 在到达时成功呈现,标签也不会显示。 让我给你看代码

@interface CustomView : UIView 

    UIImageView *imageView;
    UILabel *lbl1;
    UILabel *lbl2;
    UILabel *lbl3;
    UILabel *lbl4;


@property(nonatomic,retain) UIImageView *imageView;
@property(nonatomic,retain) UILabel *lbl1;
@property(nonatomic,retain) UILabel *lbl2;
@property(nonatomic,retain) UILabel *lbl3;
@property(nonatomic,retain) UILabel *lbl4;

而实现如下:

@implementation CustomView

@synthesize imageView;
@synthesize lbl1;
@synthesize lbl2;
@synthesize lbl3;
@synthesize lbl4;

- (id)initWithFrame:(CGRect)frame

    if ((self = [super initWithFrame:frame]))
    
        self.lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(65, 356, 98, 13)];
        self.lbl1.backgroundColor = [UIColor clearColor];
        [self addSubview:self.lbl1];

        self.lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(260, 356, 50, 13)];
        self.lbl2.backgroundColor = [UIColor clearColor];
        [self addSubview:self.lbl2];

        self.lbl3 = [[UILabel alloc] initWithFrame:CGRectMake(65, 374, 92, 13)];
        self.lbl3.backgroundColor = [UIColor clearColor];
        [self addSubview:self.lbl3];

        self.lbl4 = [[UILabel alloc] initWithFrame:CGRectMake(260, 374, 49, 13)];
        self.lbl4.backgroundColor = [UIColor clearColor];
        [self addSubview:self.lbl4];
    
    return self;

请注意,为方便起见,标签矩形是硬编码的,并且不匹配。 设置标签文本的方法示例如下:

- (void)showLbl1:(NSString *)str withFont:(UIFont *)font andColor:(UIColor *)color

    self.lbl1.font = font;
    self.lbl1.textColor = [UIColor cyanColor];
    [self.lbl1 setText:str];

图像通过 performSelectorInBackground 运行的方法传递,并通过 performSelectorOnMainThread 运行的方法绘制。 最后通过superView中的addSubView添加整个view。

提前感谢

【问题讨论】:

将标签添加为视图的子视图,如下所示 [self.view addSubview:self.lbl4]; 是否调用了showLbl1等方法? @ozzotto:你能得到我吗?如果有任何疑问? 'self' 是 UIView 的子类,所以 self.view 不存在。也许你的意思是 [superview.view addSubview:lbl1] ? @Prajan,看起来这只是一个 UIView 而不是 UIViewController,所以 'self' 应该是正确的而不是 'self.view' 【参考方案1】:

尝试绘制标签边框并查看它们的位置...还要检查那里的 uber 泄漏,您有一个 alloc init 并且从不释放标签并且还使用 setter,因此您正在执行双重分配初始化。

【讨论】:

以上是关于UILabels 未显示在 UIView 的子类中的主要内容,如果未能解决你的问题,请参考以下文章

iPhone上的UIView和UILabels上的渐变[重复]

MVC:我应该在 View Controller 或 UIView 的自定义子类中添加和实现触摸手势吗

如何将 UIView 插座连接到自定义子视图

UIView 子类:drawRect 未调用

在 UITableviewcell headerview 的 UIView 中添加动态图像

使用标签/UILabels/UIViews