0

我相信,这个问题是重复的,但我找不到它=(。如何创建自己的 UIView 类,它是从 (iPhone/iPad)*.xib 加载的

我正在尝试接下来的事情:

@interface CurtainView : UIView

...

- (id)init {
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
         self = [[[NSBundle mainBundle] loadNibNamed:@"CurtainView_iphone" owner:self options:nil] objectAtIndex:0];
        [self setFrame:CGRectMake(0, 0, 320, 460)];
    }
    else {                
        self = [[[NSBundle mainBundle] loadNibNamed:@"CurtainView_ipad" owner:self options:nil] objectAtIndex:0];
        [self setFrame:CGRectMake(0, 0, 768, 1004)];
    }
    return self;
}
- (void)drawRect:(CGRect)rect
{
    NSLog(@"there should be some animation on view appirance");

}

和 ...

CurtainView* curtain = [[CurtainView alloc] init];
NSLog(@"before");
[self.view addSubview:curtain];
[curtain drawRect:CGRectMake(0, 0, 320, 460)];

但在这种情况下,我没有得到我期望的结果,并且 drawRect 没有调用。我希望有一种简单的方法可以为通用应用程序创建自定义视图。

4

2 回答 2

0

好的。对不起,我弄错了:

它需要使用:

[self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"Curtain_iPhone" owner:self options:nil] objectAtIndex:0]];

而不是我的:

self = [[[NSBundle mainBundle] loadNibNamed:@"CurtainView_iphone" owner:self options:nil] objectAtIndex:0];

希望它对某人有所帮助。

此外,我不知道为什么,但视图的属性“不透明”应该在“init”方法中设置,而不仅仅是在 IB 中。

于 2012-04-06T09:11:53.707 回答
0

将此代码放入 .h 文件中#import

@interface CurtainView : UIView

@end

将此代码放在 .m 文件中

#import "CurtainView.h"

@implementation CurtainView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect{
   // Drawing code
   NSLog(@"there should be some animation on view appirance");
}

现在将此 UIView 称为您的 viewcontroller 类。这将调用drawRect

CurtainView* curtain = [[CurtainView alloc] init];
NSLog(@"before");
[curtain drawRect:self.view.frame];
[self.view addSubview:curtain];

你可以调用你的视图控制器类

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
     self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
 } else {
     self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
 }
于 2012-04-05T13:43:13.317 回答