gpt4 book ai didi

ios - 如何在显示之前在界面生成器(.xib)中配置子类 UIView?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:48:17 24 4
gpt4 key购买 nike

在我的应用程序中,我对 UIView 进行了子类化,它在 .m 文件中声明了三个 ivar(2UIButton 和一个 UITextField)。我通过从对象库中拖动 UIView 并将它们转换为我的子类来使用该对象。下面是我的实现

@interface Prescriber()<UITextFieldDelegate>
{
UIButton *_addButton;
UIButton *_lessButton;
UITextField *_valueField;

}
@end
@implementation Prescriber
@synthesize value=_value,intValueofStrig=_intValueofStrig;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
NSLog(@"prescriber called");
return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
-(void)layoutSubviews
{

if (!_addButton) {
_addButton=[[UIButton alloc]init];
[_addButton addTarget:self action:@selector(addbuttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[_addButton setBackgroundImage:[UIImage imageNamed:@"add1.png"] forState:UIControlStateNormal];
_addButton.layer.cornerRadius=5;

}
if (!_lessButton) {
_lessButton=[[UIButton alloc]init];
[_lessButton addTarget:self action:@selector(lessButoonClicked:) forControlEvents:UIControlEventTouchUpInside];
[_lessButton setBackgroundImage:[UIImage imageNamed:@"Minus.png"] forState:UIControlStateNormal];
}
if (!_valueField) {
_valueField=[[UITextField alloc]init];
_valueField.delegate=self;
}
///positioning the addbutton on left corner and right corner and position and
textfield in the center


}

我已经在 -(void)layoutSubviews 方法中完成了配置代码,因为我的 -initwithFrame 没有被调用,因为它们已经在 xib 文件中。我想知道的是,在 -layoutSubViews 中进行初始化是否正确,因为此方法有机会在下次调用。或者我可以调用-viewDidLoad 也像我的子类 View 的委托(delegate)方法吗?

编辑:- 通过创建 IBOutlet 是可能的,但这种方式对我来说是一个限制。

最佳答案

以私有(private)设置方法进行:

@interface MyViewClass ()
- (void)_setup;
@end

@implementation MyViewClass

- (void)_setup
{
_addButton=[[UIButton alloc]init];
[_addButton addTarget:self action:@selector(addbuttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[_addButton setBackgroundImage:[UIImage imageNamed:@"add1.png"] forState:UIControlStateNormal];
_addButton.layer.cornerRadius=5;

_lessButton=[[UIButton alloc]init];
[_lessButton addTarget:self action:@selector(lessButoonClicked:) forControlEvents:UIControlEventTouchUpInside];
[_lessButton setBackgroundImage:[UIImage imageNamed:@"Minus.png"] forState:UIControlStateNormal];

_valueField=[[UITextField alloc]init];
_valueField.delegate=self;
}

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self != nil)
{
[self _setup];
}
return self;
}

- (id)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self != nil)
{
[self _setup];
}
return self;
}

@end

关于ios - 如何在显示之前在界面生成器(.xib)中配置子类 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16602833/

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