【发布时间】:2013-04-11 09:01:07
【问题描述】:
我有一个UIView,它由两个子视图组成-
@interface ANImageLabel : UIView
@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) UILabel *label;
- (id)initWithFrameAtOrigin:(CGPoint)origin imageViewSize:(CGSize)imageViewSize labelSize:(CGSize)labelSize;
@end
- (id)initWithFrameAtOrigin:(CGPoint)origin imageViewSize:(CGSize)imageViewSize labelSize:(CGSize)labelSize
{
CGRect frame = CGRectZero;
frame.origin = origin;
// height should be the max of both heights
CGFloat height = MAX(imageViewSize.height, labelSize.height);
CGFloat width = imageViewSize.width + labelSize.width;
imageViewSize.height = labelSize.height = frame.size.height = height;
frame.size.width = width;
self = [super initWithFrame:frame];
if (self) {
// Initialization code
CGRect imageViewFrame = CGRectZero;
imageViewFrame.origin = origin;
imageViewFrame.size = imageViewSize;
self.imageView = [[UIImageView alloc] initWithFrame:imageViewFrame];
self.imageView.contentMode = UIViewContentModeCenter;
[self addSubview:self.imageView];
CGRect labelFrame = CGRectZero;
labelFrame.origin.x = origin.x + imageViewSize.width;
labelFrame.origin.y = origin.y;
labelFrame.size = labelSize;
self.label = [[UILabel alloc] initWithFrame:labelFrame];
[self addSubview:self.label];
}
return self;
}
我 alloc-init 这个视图的一个实例 (anImageLabelInstance) 在另一个视图 (mySuperView) 中,我想将它添加为子视图。
但是,如果我直接将此视图添加为子视图,则不起作用。
[mySuperView addSubview:anImageLabelInstance]; <--- DOESN'T WORK, WHY?
另一方面,如果我单独添加视图,它可以工作-
[anImageLabelInstance.subviews enumerateObjectsUsingBlock:^(UIView *view, NSUInteger idx, BOOL *stop) {
[mySuperView addSubview:view];
}];
addSubview的描述说
如果视图已经有一个超级视图并且该视图不是接收者, 这个方法在做receiver之前移除之前的superview 它的新超级视图。
但是,由于 anImageLabelInstance 在此操作之前最初并未作为子视图添加到任何其他视图中,为什么我需要单独添加视图?不应该使用addSubview 方法添加视图的所有子视图吗?
【问题讨论】:
-
“它不起作用”——这是什么意思?发生什么了?你的意思是你的视图没有出现?
-
是的,所有子视图和您要添加的主视图都会被添加。
-
尝试在您的班级中实施 - (void)dealloc 并在其中执行 NSLog。你的 NSLog 出现了吗?
-
请同时发布实例化和使用您的 uiview 子类的代码。它是如何存储的?本地变量还是属性?
标签: ios objective-c iphone ios5 addsubview