如何控制子视图的大小和布局?

时间:2012-10-09 18:23:45

标签: iphone objective-c ios ipad uiviewcontroller

我正在深入研究iOS开发,我正试图弄清楚如何控制多个子视图的大小和布局(在这种情况下,两个子视图)。我在不同的背景下发布了这个问题,我的问题没有得到回答,所以我把它作为一个更简单的问题重新发布。我正在尝试添加到子视图并将它们分别定位在(0,0)和(100,100),但我添加的第一个视图(主)最终填满整个屏幕。我的代码非常简单,我做错了什么阻止我控制两个子视图的大小和位置?

MySplitViewController.m

#import "MySplitViewController.h"
#import "MasterViewController.h"
#import "DetailViewController.h"

@interface MYSplitViewController (){}

@property (nonatomic, strong) MasterViewController *masterViewController;
@property (nonatomic, strong) DetailViewController *detailViewController;

@end

@implementation MySplitViewController

- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
      self.masterViewController = [[MasterViewController alloc] initWithNibName:nil bundle:nil];
      self.detailViewController = [[DetailViewController alloc] initWithNibName:nil bundle:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.frame = CGRectMake(0, 0, 768, 1004);
    [self.view addSubview:self.masterViewController.view];
    [self.masterViewController viewDidLoad];
    [self.view addSubview:self.detailViewController.view];
    [self.detailViewController viewDidLoad];
}

@end

MasterViewController.m

#import "MasterViewController.h"

@interface MasterViewController ()

@end

@implementation MasterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 100, 1004) style:UITableViewStylePlain];
    table.dataSource = self;
    table.delegate = self;
    [self.view addSubview:table];
}

@end

DetailViewController.m

#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *uiview = [[UIView alloc] initWithFrame:CGRectMake(100, 0, 668, 1004)];
    [self.view addSubview:uiview];
}

@end

非常感谢您的智慧!

2 个答案:

答案 0 :(得分:1)

在将self.masterViewController.view添加为子视图之前,请尝试设置self.detailViewController.viewself.view的帧。

例如: -

self.masterViewController.view.frame = CGRectMake(0, 0, 100, 100);
self.detailViewController.view.frame = CGRectMake(100, 100, 200, 200);

你不应该直接调用viewDidLoad方法。一旦视图加载到屏幕上,它就会自动调用。

答案 1 :(得分:1)

您应该为MySplitViewController视图创建UIView派生类并实现layoutSubviews方法