0

正如标题所述,我正在尝试导入 UIView,但无法使其正常工作。第一段代码显示了我在不导入任何内容的情况下尝试做的事情:

@interface ViewController : UIViewController
{

  UIView *firstUIView;
  UIView *secondUIView;

}

@end

@implementation ViewController

-(void)firstUIView
{
    firstUIView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
    firstUIView.backgroundColor = [UIColor redColor];
    [self.view addSubview:firstUIView];
}

-(void)secondUIView
{
    secondUIView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 320, 100)];
    secondUIView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:secondUIView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.

    [self firstUIView];
    [self secondUIView];

}

@end

现在下面的位没有给出相同的结果,但我想要它 - 我哪里出错了?

- (void)viewDidLoad
   {
     [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

     firstUIViewExternal *firstUIView = [[firstUIViewExternal alloc]     initWithFrame:CGRectMake(0, 0, 320, 300)];
     secondUIViewExternal *secondUIView = [[secondUIViewExternal alloc] init];


     [self.view insertSubview:firstUIView aboveSubview:self.view];
     [self.view addSubview:secondUIView];

    }

    @end

firstUIViewExternal 和 secondViewExternal 的代码相同,只是名称不同,如下:

-(void)secondUIView
 {
     secondUIView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 320, 100)];
     secondUIView.backgroundColor = [UIColor blueColor];
     [self addSubview:secondUIView];
 }

然后使用 #imported 导入它们,在上面的 -(void)viewDidLoad 方法中声明使用。

为什么导入的版本不起作用?

如果需要,我会提供任何额外的信息。谢谢:-)

这是我想通过导入 UIViews 来实现的,但我得到的是一个空白的白色:

在此处输入图像描述

4

1 回答 1

1

我在您的代码中注意到两件事:

  1. 您没有指定 secondUIView 的帧大小。
  2. 您只需要覆盖“UIViewExternal”视图中的 initWithFrame 方法并从您的 UIView 继承。

您要导入的视图的代码应如下所示:

。H:

#import <UIKit/UIKit.h>
@interface firstUIViewExternal : UIView
@end

米:

#import "firstUIViewExternal.h"
@implementation
   - (id)initWithFrame:(CGRect)frame
   {
        self = [super initWithFrame:frame];
        if (self) {
                // Initialization code
                self.backgroundColor = [UIColor blueColor];
        }
        return self;
    }
@end 
于 2012-09-13T22:25:13.580 回答