【问题标题】:Create TableView in some UIView, Objective c在一些 UIView 中创建 TableView,Objective c
【发布时间】:2017-09-06 22:02:48
【问题描述】:

在我的ViewController 中有一点UIView。如何以编程方式创建 TableView 而不是这个“蓝色”UIView

我的UIView 有这个代码。

self.viewForTableView = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2,
                                                                 self.navigationController.navigationBar.frame.size.height,
                                                                 self.view.frame.size.width/2,
                                                                 self.view.frame.size.height)];
self.viewForTableView.backgroundColor = [UIColor blueColor];
[self.view addSubview:self.viewForTableView];

这就是我想要的preview

【问题讨论】:

    标签: ios objective-c iphone uitableview uiview


    【解决方案1】:

    斯威夫特

    let tblVW:UITableView = UITableView(frame: viewForTableView.frame)
    viewForTableView.addSubview(tblVW)
    tblVW.delegate = self
    tblVW.dataSource = self
    

    目标-c

     UITableView *tblView = [[UITableView alloc]initWithFrame:viewForTableView.frame];
    [viewForTableView addSubview:tblView];
    tblView.delegate = self;
    tblView.dataSource = self;
    

    您需要实现以下方法:

    #pragma mark - Table View Data source 
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
       return 0//number rows you want in table
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *cellIdentifier = @"cellID";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:
            UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        return cell;
    }
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 2; //by default is 1
    }
    

    【讨论】:

    【解决方案2】:

    viewcontroller.h

    @interface yourViewController ()<UITableViewDelegate,UITableViewDataSource>
    
    {
    IBOutlet UITableView *tbleView;
    
    }
    

    Viewcontroller.m

    - (void)viewDidLoad {
    
    [super viewDidLoad];
    tbleView.delegate=self;//for delegate methods 
    tbleView.datasource=self;//for datasource methods
    tbleView.backgroundColor=//yourColor
    tbleView.frame=CGRectMake(//your frame);
    [yourView addSubview tbleView];
    
    }
    

    【讨论】:

    • 你不应该在 viewDidLoad 中设置框架!
    • 需要给table view的frame。
    • 使用loadView 而不是viewDidLoad
    猜你喜欢
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 2010-11-05
    相关资源
    最近更新 更多