2

I am trying to subclass a UIView using the nib. Using the following code:


- (void)awakeFromNib
{
    [super awakeFromNib];
    NSArray *v = [[NSBundle mainBundle] loadNibNamed:@"Qus_Scale1to7View" owner:self options:nil];
    [self addSubview:[v objectAtIndex:0]];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        NSArray *v = [[NSBundle mainBundle] loadNibNamed:@"Qus_Scale1to7View" owner:self options:nil];
        [self addSubview:[v objectAtIndex:0]];
    }
    return self;
}

this creates the object correctly and view also displayed and when the object loads from its nib the delegate instantly becomes null and ignores any attempt to assign values to it.

Can anyone know the reason why it is?

Thanks in advance.

4

2 回答 2

3

它不会为多个视图控制器重用相同的 xib。如果您想重用该视图,请创建一个继承自 UIView 的类并在其中添加代码。

#import "SomeProtocol.h"

@interface MyCustomView : UIView {
    IBOutlet UIView *headerView;
    IBOutlet UIView *footerView;
    IBOutlet UIButton *updateBtn;
}

@property (nonatomic, assign) id<SomeProtocol> delegate;

@end

............

@implementation BCFirmwareView

@synthesize delegate = _delegate;

+ (id)viewFromNibWithName: (NSString*)name {
    UIView *view = nil;
    NSArray *views = [[NSBundle mainBundle] loadNibNamed: name owner: self options: nil];
    if (views) {
        for (UIView *aView in views) {
            if ([aView isKindOfClass: NSClassFromString(name)])
                view = aView;
        }
    }

    return view;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder: aDecoder];

    if (self) {
    }

    return self;
}

- (id)init {
    self = [[MyCustomView viewFromNibWithName: @"MyCustomView"] retain];
    if (self) {
    }

    return self;
}

- (void)dealloc {
    self.delegate = nil;

    [headerView release];
    [footerView release];
    [updateBtn release];

    [super dealloc];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Do any additional setup after loading the view from its nib.

    headerView.backgroundColor = [UIColor redColor];
    footerView.backgroundColor = [UIColor greenColor];
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview: newSuperview];

    if (!newSuperview)
        return;
}

- (void)didMoveToSuperview {
    [super didMoveToSuperview];
}

- (IBAction)updateBtnPressed: (id)sender {
// do some stuff
}

@end

下一步是在 Interface Builder 中打开 xib 并将您的类设置为视图的自定义类,而不是文件的响应程序。右键单击视图并建立插座和操作连接。

更改视图的自定义类

为视图建立出口和动作连接

现在您应该能够在任何视图控制器中简单地创建 MyCustomView 的实例并使用它。如果您没有忘记将视图自定义类更改为您的类,则也可以在 Interface Builder 中使用。

于 2013-07-05T15:06:42.110 回答
0

您可以使用 Xib 创建自定义 UIView 并向其添加属性。然后将类与 xib 链接,并将属性与 IB 链接。

或者您只能使用

NSArray *v = [[NSBundle mainBundle] loadNibNamed:@"Qus_Scale1to7View" owner:self options:nil];

UIView *view = [v objectAtIndex:0];

并使用viewWithTag:方法设置您的对象值。

UILabel *label = (UILabel *)[view viewWithTag:yourTag];

让我知道这是否有帮助。

于 2013-07-05T11:41:39.440 回答