陈斌彬的技术博客

Stay foolish,stay hungry

iOS在一个viewController中添加另一个viewController

新建SearchViewController.h文件

#import <UIKit/UIKit.h>

@interface SearchViewController : UITableViewController 

@end

在SearchViewController.m中

//
//  SearchViewController.m
//  HangyuHealth
//
//  Created by ChenBinbin on 16/3/10.
//  Copyright © 2016年 AntWork. All rights reserved.
//

#import "SearchViewController.h"

@interface SearchViewController ()

@end

@implementation SearchViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.layer.borderWidth = 1;
    self.tableView.layer.borderColor = [[UIColor blackColor] CGColor];
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 返回列表框的下拉列表的数量
    return 3;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    }

    cell.textLabel.text = @"binbin";

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"点击了哪行 %d",indexPath.row);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

在另一个ViewController中添加子控制器

    SearchViewController *searchController = [[SearchViewController alloc] initWithStyle:UITableViewStylePlain];
    [searchController.view setFrame:CGRectMake(10, 2, 300, 180)];
    [self.view addSubview:searchController.view];
    [self addChildViewController:searchController];