jjzjj

ios - 如何将 Storyboard中的 UITableViewCell 添加到以编程方式创建的 UITableView 对象?

coder 2024-01-29 原文

在我的 iOS 应用程序中,我有带有两个选项卡的选项卡栏,如下所示。对于每个选项卡,我都以编程方式创建了 UITableView 对象。

我使用 Collection View 创建了标签栏。接下来,我从 Storyboard 中将 UITableViewCell 添加到我的 View Controller 。

所以我得到了以下 View 。

但现在当我运行我的应用程序时,我看不到 UItableviewcell。我犯错的地方我不明白。请帮忙。

下面是我的代码。

#import "TicketsViewController.h"
#import "TabBarCollectionViewCell.h"
#import "TicketTableViewCell.h"
#import "Constants.h"

@interface TicketsViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UICollectionView *tabBarCollectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *tabBarCollViewFlowLayout;
@property (weak, nonatomic) NSIndexPath *prevSelecedIndexPath;
@property (strong, nonatomic) NSArray *tabBarItemNamesArray;
@property (weak, nonatomic) IBOutlet UIView *parentViewForTableViews;
@property (weak, nonatomic) UIView *previousView;
@property (strong, nonatomic) NSMutableArray *tabRespectiveTableViewsArray;

@end

@implementation TicketsViewController

#pragma mark - lazy instantiation

- (NSArray *)tabBarItemNamesArray {
    if (!_tabBarItemNamesArray)
        _tabBarItemNamesArray = @[@"All Tickets", @"Resolved Tickets"];

    return _tabBarItemNamesArray;
}

- (NSMutableArray *)tabRespectiveTableViewsArray {
    if (!_tabRespectiveTableViewsArray)
        _tabRespectiveTableViewsArray = [[NSMutableArray alloc] initWithArray:@[(id)[NSNull null], (id)[NSNull null]]];

    return _tabRespectiveTableViewsArray;
}

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view layoutIfNeeded];

    [self tabBarItemNamesArray];
    [self tabRespectiveTableViewsArray];

    _tabBarCollectionView.delegate = self;
    _tabBarCollectionView.dataSource = self;
    _previousView = nil;

    _tabBarCollViewFlowLayout.itemSize = CGSizeMake(ceilf(_tabBarCollectionView.frame.size.width / 2), _tabBarCollViewFlowLayout.itemSize.height);

    _prevSelecedIndexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    [_tabBarCollectionView selectItemAtIndexPath:_prevSelecedIndexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

#pragma mark - collection view

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _tabBarItemNamesArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TabBarCollectionViewCell *tabBarCollectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TabBarCollectionViewCell" forIndexPath:indexPath];

    tabBarCollectionViewCell.tabView.tabTitle = [_tabBarItemNamesArray objectAtIndex:indexPath.row];
    if ([_tabRespectiveTableViewsArray objectAtIndex:indexPath.row] == (id)[NSNull null]) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:_parentViewForTableViews.bounds style:UITableViewStylePlain];
        [tableView registerClass:[TicketTableViewCell class] forCellReuseIdentifier:@"TicketTableViewCell"];

        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.showsVerticalScrollIndicator = YES;
        tableView.showsHorizontalScrollIndicator = NO;
        tableView.scrollEnabled = YES;
        tableView.pagingEnabled = NO;
        tableView.bounces = YES;
        tableView.userInteractionEnabled = YES;
        tableView.backgroundColor = [UIColor clearColor];

        tableView.translatesAutoresizingMaskIntoConstraints = NO;
        [_parentViewForTableViews addSubview:tableView];
        [_tabRespectiveTableViewsArray replaceObjectAtIndex:indexPath.row withObject:tableView];

        [_parentViewForTableViews addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[v0]|" options:0 metrics:nil views:@{@"v0" : tableView}]];

        if (_previousView == nil) {
            [_parentViewForTableViews addConstraint:[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_parentViewForTableViews attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f]];
            _previousView = tableView;
        }
        else {
            [_parentViewForTableViews addConstraint:[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_previousView attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:0.0f]];
        }

        [_parentViewForTableViews addConstraint:[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_parentViewForTableViews attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]];

        tableView.dataSource = self;
        tableView.delegate = self;
    }

    return tabBarCollectionViewCell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    ((TabBarCollectionViewCell *)cell).tabView.tabSelected = cell.isSelected;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_prevSelecedIndexPath)
        ((TabBarCollectionViewCell *)[collectionView cellForItemAtIndexPath:_prevSelecedIndexPath]).tabView.tabSelected = NO;
    ((TabBarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath]).tabView.tabSelected = YES;
    _prevSelecedIndexPath = indexPath;

    [collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    [((UITableView *)[_tabRespectiveTableViewsArray objectAtIndex:indexPath.row]) reloadData];
}

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    ((TabBarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath]).tabView.tabHighlighted = YES;
}

- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    ((TabBarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath]).tabView.tabHighlighted = NO;
}

#pragma mark - table view

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TicketTableViewCell *ticketTableViewCell = [tableView dequeueReusableCellWithIdentifier:@"TicketTableViewCell" forIndexPath:indexPath];

    ticketTableViewCell.labelTime.text = @"02:45 PM";

    return ticketTableViewCell;
}

#pragma mark - button actions

- (IBAction)buttonOpenDrawerAction:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:SHOW_LEFT_DRAWER object:self];
}

@end

最佳答案

您的代码工作几乎是正确的,但为了更好的编码风格,请遵循:

  1. 据我了解,您的 UITableView 位于 UICollectionViewCell 中,因此请为您的 View 编写层次结构代码,即执行 UITableView 代码在 UICollectionViewCell 文件中。将 UITableView delegate\datasouceUICollectionViewCell 文件绑定(bind)并绑定(bind) UICollectionView 委托(delegate)\datasouceUIViewController。它使您可以轻松管理所有组件。

  2. 每当您对任何组件施加约束时,您也必须激活该约束,现在我看不到任何约束激活代码,或者可能是我的眼睛错过了它。

  3. 根据您的 UI 屏幕截图,我认为您不需要为 All TicketsResolved Tickets< 分别获取两个="">UITableView/strong> 因为在特定时间用户选择所有工单已解决的工单。因此,采用一个 UITableView 并使用 reload tableview 属性并更改表格数据。

  4. 你已经完成了 storyboard 的一半工作,我认为你不需要以编程方式创建 UITableView,因为你的 UITableView 不会在运行时改变,只需改变它的数据。

Edit

如何在 UI 上显示带有滚动效果的数据。

直到您的标题选项选择正确。

  1. 对于下方的黄色 View ,需要额外的 UIcollectionView

  2. UIcollectionView 的滚动属性设置为水平滚动。

  3. 创建一个UIcollectionViewcell,并在其中添加UITableView
  4. 您的 UIcollectionViewcell 具有黄色 View 的大小。
  5. 要保持 UIcollectionViewcell 高度,您必须计算其内部 tableView 高度并使用 UICollectionViewDelegateFlowLayout< 调整="">UIcollectionViewcell 高度 sizeForItemAtIndexPath; 方法。
  6. collectionView 中使用分页以获得更好的拖动效果并根据您的要求正确更新您的数据。
  7. 要在单个类中管理多个集合,请在 cellforItem

    中使用以下代码

    if(collectionView == tabCollectionView ){ //在这里为选项卡集合编写代码 } 别的{ //在这里为数据 collectionView 编写代码 }

关于ios - 如何将 Storyboard中的 UITableViewCell 添加到以编程方式创建的 UITableView 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41735091/

有关ios - 如何将 Storyboard中的 UITableViewCell 添加到以编程方式创建的 UITableView 对象?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  4. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  5. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  6. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  7. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  8. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  9. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  10. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

随机推荐