自定义查看通用应用程序

时间:2012-04-05 13:11:07

标签: iphone ipad universal

我相信,这个问题是重复的,但我找不到它=(。 如何创建自己的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没有调用。我希望有一种简单的方法可以为通用应用程序创建自定义视图。

2 个答案:

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

你可以调用你的viewcontroller类

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
     self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
 } else {
     self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
 }

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

希望它对某些人有帮助。

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