草庐IT

objective-c - 插入 UITableViewCell 不工作

coder 2024-01-10 原文

有人可以解释一下我在尝试插入新的 UITableViewCell 时做错了什么吗?我正在尝试插入自定义 UITableViewCell,但它会引发以下错误:“无效更新:第 0 节中的行数无效。更新后现有部分中包含的行数 (1) 必须等于数字更新前该部分中包含的行数 (1),加上或减去从该部分插入或删除的行数(插入 1,删除 0),加上或减去移入或移出该部分的行数(0搬进来,0 搬出去)。'

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (section == 0)
    return 1;
else if (section == 1)
    return numberOfRows;
return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EditableCell";

EditableCell *editableCell = (EditableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (editableCell == nil) {

    editableCell = [[EditableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

_myTextField = [editableCell textFieldCell];

if (indexPath.section == 0){
    [_myTextField setPlaceholder:@"Menu Name"];
    [_myTextField setReturnKeyType:UIReturnKeyNext];
}
else if (indexPath.section == 1){
    [_myTextField setPlaceholder:@"Category"];
    [_myTextField setReturnKeyType:UIReturnKeyNext];
}
else {
    [_myTextField setPlaceholder:@"Category"];
    [_myTextField setReturnKeyType:UIReturnKeyDone];
}

_myTextField.keyboardType = UIKeyboardTypeDefault;
_myTextField.delegate = self;

return editableCell;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

if (textField.returnKeyType == UIReturnKeyNext) {

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    NSArray *array = [[NSArray alloc] initWithObjects:indexPath, nil];

    [self.tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationTop];

    numberOfRows = numberOfRows + 1;

    [self.tableView reloadData];
    }     
}

最佳答案

您需要确保下面方法中返回的行数现在返回正确的行数。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

我确定发生的事情是您在插入后返回相同的值,而运行时期望它比调用插入行之前多 1。

更详细一点,在 MVC 术语(模型/ View / Controller )中发生的事情是这样的:

  1. 您对 insertRowsAtIndexPaths 的调用请求 Controller 使用额外的行更新 View。
  2. Controller 然后进行健全性检查以查看您的总和是否正确,因此它会调用: tableView:numberOfRowsInSection

    现在 Controller 知道此方法上次返回的值(在您的情况下为 1),并且它还知道您已请求插入一行。没有 delete 调用,因此它预计下次调用此方法时,值应该是(上次的值 + 插入的行 - 删除的行)= 2

  3. 如果 Controller 认为您的事情是有序的,它将调用 cellForRowAtIndexPath(以及其他方法)以获取每个部分中每一行的实际单元格。

因此,对于您的问题,您需要跟踪模型中的行 - 也许在一个数组或一个具有可用行数的 ivar 中。通过在调用 insertRowsAtIndexPath 之前添加/删除行时更新此值来更新模型,然后在 tableView:numberOfRowsInSection 时返回此值> 被调用。

额外提示:

如果您希望单元格插入/删除具有动画效果,请将您的代码更改为以下内容。请注意,不再调用 reloadData,而是插入/重新加载包含在开始/结束更新调用中 - 由于 ,动画更新将在 endUpdates 之后发生reloadSections 调用。

NSMutableIndexSet *sectionsToReload = [[NSMutableIndexSet alloc] init];
[sectionsToReload addIndex:1]; // Add sections as necessary

[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationTop];
[self.tableView reloadSections:sectionsToReload withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

查看 WWDC 2010 video from Apple ,“掌握 TableView ”- 很好地解释了有关使用 insertRowsAtIndexPaths 和相关方法的所有内容。

喂, 拉伸(stretch)

关于objective-c - 插入 UITableViewCell 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11129986/

有关objective-c - 插入 UITableViewCell 不工作的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  5. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  6. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  7. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  8. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  9. ruby - JetBrains RubyMine 3.2.4 调试器不工作 - 2

    使用Ruby1.9.2运行IDE提示说需要gemruby​​-debug-base19x并提供安装它。但是,在尝试安装它时会显示消息Failedtoinstallgems.Followinggemswerenotinstalled:C:/ProgramFiles(x86)/JetBrains/RubyMine3.2.4/rb/gems/ruby-debug-base19x-0.11.30.pre2.gem:Errorinstallingruby-debug-base19x-0.11.30.pre2.gem:The'linecache19'nativegemrequiresinstall

  10. ruby - `rescue $!` 是如何工作的? - 2

    我知道全局变量$!包含最新的异常对象,但我对下面的语法感到困惑。谁能帮助我理解以下语法?rescue$! 最佳答案 此构造可防止异常停止您的程序并使堆栈跟踪冒泡。它还会将该异常作为值返回,这很有用。a=get_me_datarescue$!在此行之后,a将保存请求的数据或异常。然后您可以分析该异常并采取相应措施。defget_me_dataraise'Nodataforyou'enda=get_me_datarescue$!puts"Executioncarrieson"pa#>>Executioncarrieson#>>#更现实的

随机推荐