gpt4 book ai didi

ios - 为什么从自定义 UIView 向 UIButton 添加 subview 不显示添加的 subview ?

转载 作者:行者123 更新时间:2023-11-29 10:57:01 24 4
gpt4 key购买 nike

我有一个 UIView 的子类,我正在从一个 NIB 文件中加载它。我的 NIB 文件包含一个 UIButton 和一个 IBOutlet,称为 clock

@property (strong, nonatomic) IBOutlet UIButton *clock;

在我的界面生成器上我的时钟按钮中设置的文本显示出来了!但是我从 initWithCoder 添加的其他 subview 却没有。这是为什么?

.h文件

@interface TWTimerView : UIView

@property (strong, nonatomic) IBOutlet UIButton *clock;

@property (strong, nonatomic) UIImageView *circle;
@property (strong, nonatomic) UIImageView *pointer;
@property (strong, nonatomic) UIImageView *tick;

@property (strong, nonatomic) UIImageView *circleGlow;
@property (strong, nonatomic) UIImageView *pointerGlow;
@property (strong, nonatomic) UIImageView *tickGlow;

@end

.m 文件

@implementation TWTimerView

-(id)initWithCoder:(NSCoder *)aDecoder {

self = [super initWithCoder:aDecoder];
if(self) {

self.backgroundColor = [UIColor clearColor];

_circle = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"circle"]];
_pointer = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pointer"]];
_tick = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tick"]];

[_clock addSubview:_circle];
[_clock addSubview:_pointer];
[_clock addSubview:_tick];

}
return self;
}

- (id)initWithFrame:(CGRect)frame
{

self = [super initWithFrame:frame];
if (self) {
// Initialization code
TWTimerView *view= [[[NSBundle mainBundle] loadNibNamed:@"TimerView" owner:self options:nil] objectAtIndex:0];
[self addSubview:view];

}
return self;
}

@end

谢谢!

最佳答案

这是我会做的:如果您不需要使用框架,请删除 initWithFrame 方法并使用另一种方法来帮助您加载 View ,如下所示。

+ (id)loadViewFromNIBFile {
NSArray * array = [[NSBundle mainBundle] loadNibNamed:@"TimerView" owner:self options:nil];
//You may want to assert array only contains one element here
TWTimerView * view = (TWTimerView *)[array objectAtIndex:0];
NSAssert([view isKindOfClass:TWTimerView.class], @"Unexpected class");
[view _setDefaultComponents];
return view;
}

- (void)_setDefaultComponents {
self.backgroundColor = [UIColor clearColor];
_circle = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"circle"]];
_pointer = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pointer"]];
_tick = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tick"]];
[_clock addSubview:_circle];
[_clock addSubview:_pointer];
[_clock addSubview:_tick];
}

调用 [TWTimerView loadViewFromNIBFile] 获取您的 View 实例。

关于ios - 为什么从自定义 UIView 向 UIButton 添加 subview 不显示添加的 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17809832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com