草庐IT

ios - UITableViewCell 为不同的方向和单元格类型加载自定义 XIB

coder 2024-01-26 原文

我有一个名为 ProductiPadCell 的自定义单元类,专为 iPad 设计。 (iOS 5 开发工具包)

我想要实现的是根据当前状态(展开或未展开)和界面方向加载我的自定义单元格。我在 View Controller 中处理这两种情况,问题是我不喜欢它的性能。我没有为下面定义的任何 xib 定义了一个 cellIdentifier,最近我检测到我的 tableViewcellForRowAtIndexPath:

ProductiPadCell 有 4 个不同的 XIB;

ProductiPadCell-Regular.xib
ProductiPadCell-Regular-Landscape.xib
ProductiPadCell-Expanded.xib
ProductiPadCell-Expanded-Landscape.xib

ProductiPadCell定义;

@interface ProductiPadCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIButton *detailButton;
@property (weak, nonatomic) IBOutlet UILabel *productDescriptionLabel;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *timeLabel;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *def1Label;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *def2Label;
@property (weak, nonatomic) IBOutlet UIImageView *thumbnail;
    // appears in case the cell is expanded
    @property (weak, nonatomic) IBOutlet UIView *detailHolderView;
    @property (weak, nonatomic) IBOutlet UILabel *detailLabel;
// calls a method at the superview's ViewController
- (void)presentDetailViewWithIndex:(NSInteger)index;
@end

TableView 的 cellForForAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // table identifier does not matches the xib's cell identifier
    // cell identifier of all 4 xibs are "" (empty)

    static NSString *simpleTableIdentifier = @"Cell";
    BOOL isExpanded = [[[targetDictionary objectForKey:@"isItemExpanded"] objectAtIndex:indexPath.row] boolValue];

    ProductiPadCell *cell = (ProductiPadCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) 
    {
        // Load the required nib for the current orientation and detail selection style
        if (deviceOrientation == UIDeviceOrientationPortrait) {
            if (isExpanded) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ProductiPadCell-Regular-Expanded" owner:self options:nil];
                cell = [nib objectAtIndex:0];
                // additional settings for expanded case
            }
            else {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ProductiPadCell-Regular" owner:self options:nil];
                cell = [nib objectAtIndex:0];
                // additional settings for NOT expanded case                    
            }   
        }
        else {     
            if (isExpanded) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ProductiPadCell-Landscape-Expanded" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            else {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ProductiPadCell-Regular-Landscape" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
        }
    }

    // connect cell information with cell IBOutlets
    cell.productDescriptionLabel.text = [[targetDictionary objectForKey:@"key"] objectAtIndex:indexPath.row];
    // ....

    [cell.thumbnail setImage:[UIImage imageNamed:@"thumb_image.jpg"]];
    [cell.thumbnail.layer setCornerRadius:7.0f];
    [cell.thumbnail.layer setBorderWidth:5.0f];
    [cell.thumbnail.layer setBorderColor:[UIColor clearColor].CGColor];
    [cell.thumbnail setClipsToBounds:YES];

    if (isExpanded) {
        cell.detailLabel.text = [[targetDictionary objectForKey:@"key"] objectAtIndex:indexPath.row];

    }

    return cell;
}

除了我目前的方法之外,我应该怎么做才能加载我的 xib?在每次方向更改和按钮单击时,我都会调用 [tableView reloadData],因为 dequeueReusableCellWithIdentifier:simpleTableIdentifier 找不到它总是创建新单元格的 simpleTableIdentifier。如果我将 simpleIdentifier 定义到我的单元格 xib,它们在大小写更改(方向更改、扩展状态更改)期间不会更改。

细胞标识符的最佳用途是什么?我是否应该使用 dequeueReusableCellWithIdentifier:simpleTableIdentifier

以外的其他方法

我正在等待针对我当前情况的任何解决方案,因为我确信一遍又一遍地加载每个单元格并不是最有效的方法。

最佳答案

这是一种方式,缓存nib

综合这个属性

@property (nonatomic, strong) id cellNib;

@synthesize cellNib = _cellNib;

制作自定义 setter/getter

-(id)cellNib
{
    if (!_cellNib) 
    {
        Class cls = NSClassFromString(@"UINib");
        if ([cls respondsToSelector:@selector(nibWithNibName:bundle:)]) 
        {
            _cellNib = [[cls nibWithNibName:@"SomeCell" bundle:[NSBundle mainBundle]] retain];
        }
    }

    return _cellNib;
}

viewDidLoad

[self.tableView registerNib:[UINib nibWithNibName:@"SomeCell" bundle:nil] forCellReuseIdentifier:kCellIdentification];

tableView:cellForRowAtIndexPath:

SomeCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentification];
    if (cell == nil) 
    {
        //If nib cache
        if ([self cellNib]) {
            NSArray* viewFromNib = [[self cellNib] instantiateWithOwner:self options:nil];
            cell = (SomeCell *)[viewFromNib objectAtIndex:0];
        }else { //nib not cache
            NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"SomeCell" owner:nil options:nil];
            cell = (SomeCell *)[views objectAtIndex:0];
        }
    }

希望对你有帮助

关于ios - UITableViewCell 为不同的方向和单元格类型加载自定义 XIB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14960216/

有关ios - UITableViewCell 为不同的方向和单元格类型加载自定义 XIB的更多相关文章

  1. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  4. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  5. ruby-on-rails - 如何在 Rails 3 中创建自定义脚手架生成器? - 2

    有这些railscast。http://railscasts.com/episodes/218-making-generators-in-rails-3有了这个,你就会知道如何创建样式表和脚手架生成器。http://railscasts.com/episodes/216-generators-in-rails-3通过这个,您可以了解如何添加一些文件来修改脚手架View。我想把两者结合起来。我想创建一个生成器,它也可以创建脚手架View。有点像RyanBates漂亮的生成器或web_app_themegem(https://github.com/pilu/web-app-theme)。我

  6. ruby-on-rails - Prawn - 表格单元格内的链接 - 2

    我正在尝试用Prawn生成PDF。在我的PDF模板中,我有带单元格的表格。在其中一个单元格中,我有一个电子邮件地址:cell_email=pdf.make_cell(:content=>booking.user_email,:border_width=>0)我想让电子邮件链接到“mailto”链接。我知道我可以这样链接:pdf.formatted_text([{:text=>booking.user_email,:link=>"mailto:#{booking.user_email}"}])但是将这两行组合起来(将格式化文本作为内容)不起作用:cell_email=pdf.make_c

  7. ruby-on-rails - 事件管理员日期过滤器日期格式自定义 - 2

    是否有简单的方法来更改默认ISO格式(yyyy-mm-dd)的ActiveAdmin日期过滤器显示格式? 最佳答案 您可以像这样为日期选择器提供额外的选项,而不是覆盖js:=f.input:my_date,as::datepicker,datepicker_options:{dateFormat:"mm/dd/yy"} 关于ruby-on-rails-事件管理员日期过滤器日期格式自定义,我们在StackOverflow上找到一个类似的问题: https://s

  8. ruby-on-rails - 从应用程序中自定义文件夹内的命名空间自动加载 - 2

    我们目前正在为ROR3.2开发自定义cms引擎。在这个过程中,我们希望成为我们的rails应用程序中的一等公民的几个类类型起源,这意味着它们应该驻留在应用程序的app文件夹下,它是插件。目前我们有以下类型:数据源数据类型查看我在app文件夹下创建了多个目录来保存这些:应用/数据源应用/数据类型应用/View更多类型将随之而来,我有点担心应用程序文件夹被这么多目录污染。因此,我想将它们移动到一个子目录/模块中,该子目录/模块包含cms定义的所有类型。所有类都应位于MyCms命名空间内,目录布局应如下所示:应用程序/my_cms/data_source应用程序/my_cms/data_ty

  9. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  10. ruby-on-rails - Rails - 使用/自定义 URL : '/dashboard' 指定根路径 - 2

    如何使此根路径转到:“/dashboard”而不仅仅是http://example.com?root:to=>'dashboard#index',:constraints=>lambda{|req|!req.session[:user_id].blank?} 最佳答案 您可以通过以下方式实现:root:to=>redirect('/dashboard')match'/dashboard',:to=>"dashboard#index",:constraints=>lambda{|req|!req.session[:user_id].b

随机推荐