UIView子类与使用NIB的委托

时间:2013-07-05 11:32:38

标签: ios objective-c xcode

我正在尝试使用nib子类化UIView。使用以下代码:


- (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;
}

这会正确创建对象并显示视图,当对象从其笔尖加载时,委托会立即变为空,并忽略任何为其赋值的尝试。

任何人都可以知道原因吗?

提前致谢。

2 个答案:

答案 0 :(得分: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,并将您的类设置为视图的自定义类,而不是文件的响应程序。右键单击视图并进行插座和操作连接。

change the custom class for the view

make the outlet and actions connections for the view

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

答案 1 :(得分: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];

如果有帮助,请告诉我。