【问题标题】:change tableview row height in ios 5在 ios 5 中更改 tableview 行高
【发布时间】:2011-12-07 09:36:22
【问题描述】:

在 ios 5 之前,我会像这样在 tableview 中设置行高:

self.tableView.rowHeight=71;

但是,它不适用于 iOS5。

有人有想法吗?

谢谢

【问题讨论】:

    标签: uitableview ios5


    【解决方案1】:

    你试过从UITableViewDelegatetableView:heightForRowAtIndexPath:吗?

    您可以通过在您的UITableView 委托(支持UITableViewDelegate 协议的人)中实现tableView:heightForRowAtIndexPath: 来将行高设置为71。

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        return 71.0;
    }
    

    首先你应该设置你的 tableView 的委托。委托应符合UITableViewDelegate 协议。假设我们有一个TableDelegate 类。为了符合UITableViewDelegate 协议,应该在它的声明中将它放在方括号中,如下所示:

    ...    
    @interface TableDelegate : UIViewController <UITableViewDelegate>
    ...
    or
    @interface TableDelegate : UIViewController <some_other_protocol, UITableViewDelegate>
    

    然后你设置委托:

    ...
    // create one first
    TableDelegate* tableDelegate = [[TableDelegate alloc] init];
    ...
    self.tableView.delegate = tableDelegate;
    

    最后你应该在TableDelegate实现中实现tableView:heightForRowAtIndexPath:方法:

    @implementation TableDelegate
    ...
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        return 71.0;
    }
    ...
    @end
    

    行高

    澄清一下,正如 Javier Soto 在 cmets 中指出的那样,使用 rowHeight 应该可以正常工作并且比从 -tableView:heightForRowAtIndexPath: 返回的常量更好。另请注意,如果您的 UITableView 在 -tableView:heightForRowAtIndexPath:rowHeight 属性集中有委托返回高度,则优先值是受尊重的。

    【讨论】:

    • 检查 Apple 关于使用此实现而不是设置 rowHeight 的警告:使用 tableView:heightForRowAtIndexPath: 代替 rowHeight 属性会影响性能。每次显示表视图时,它都会在委托上为其每一行调用 tableView:heightForRowAtIndexPath:,这可能会导致表视图具有大量行(大约 1000 或更多)时出现严重的性能问题。
    【解决方案2】:

    我正在为 iOS 5 编写代码,它确实有效。你只需要实现你在中所说的那一行:

     - (void)viewDidLoad
    

    之后的方法:

    [super viewDidLoad];
    

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
    

    如果 TableView 为空,则该方法不起作用。但是如果你使用 rowHeight 属性,即使视图是空的,它也会起作用。

    【讨论】:

      【解决方案3】:

      这个方法是改变行的高度

      -(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
      {
          return  51.0f
      };
      

      【讨论】:

        【解决方案4】:

        尝试设置rowHeight 之前 viewWillAppear:,例如在创建表格视图之后。

        这使它在 iOS 5 上适用于我。在 iOS 6 上它更容易:您可以在任何地方设置它。

        正如其他人所指出的,使用rowHeight 的优点是可以避免tableView:heightForRowAtIndexPath: 对性能的影响。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-29
          • 2020-01-24
          • 1970-01-01
          • 1970-01-01
          • 2015-12-03
          • 2017-07-01
          • 2013-11-15
          • 2013-01-16
          相关资源
          最近更新 更多