【问题标题】:becomeFirstResponder() does not workbecomeFirstResponder() 不起作用
【发布时间】:2016-01-03 23:23:38
【问题描述】:

我目前正在尝试创建一个类似于 Apple 提醒 的待办事项应用程序。现在,当我通过单击UIButton 添加新任务时,会创建一个包含UITextfield 的新单元格并将其分配为第一响应者。但是,当我这样做时,键盘按预期显示,但没有光标,也无法编辑。当我再次单击文本字段时,我可以按预期进行编辑。

任何帮助将不胜感激。

@IBAction func addTask(sender: UIBarButtonItem)
{

    // Add a new task
    let newIndexPath = NSIndexPath(forRow: tasks.count, inSection: 0)
    let task = Task(name: "")!
    tasks.append(task)
    tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
    let cellIdentifier = "TaskTableViewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: newIndexPath) as! TaskTableViewCell


    let db_Task = PFObject(className: "Task")
    db_Task["TaskName"] = ""
    db_Task["Completed"] = false
    db_Task["group"] = getGroupId()
    db_Task.saveInBackgroundWithBlock
        {(success: Bool, error:  NSError?) -> Void in
            print("Object has been saved.")
    }
    cell.nameLabel.becomeFirstResponder()
}

【问题讨论】:

  • nameLabel 是您的文本字段吗?刚想到名字……

标签: ios swift uitableview uitextfield


【解决方案1】:
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
let cellIdentifier = "TaskTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: newIndexPath) as! TaskTableViewCell

你不能通过'dequeue'方法得到插入的单元格。切勿从cellForIndexPath 中调用此方法。插入后你应该这样做:

let cell = tableView.cellForIndexPath(indexPath)

【讨论】:

  • 一旦我这样做了,我只能做 cell.textLabel.becomeFirstResponder() 还是不行
  • @KennyTao 插入后你删除了原来的下两行吗?
  • 我想通了。我必须将我的单元格设置为我的自定义单元格类名称,您的建议非常有效!非常感谢:)
【解决方案2】:

你可以试试

self.view.endEditing

【讨论】:

    【解决方案3】:

    BecomeFirstResponder 应该在您想要聚焦的对象上调用。在这种情况下,cell.nameLabel 是错误的对象。

    你应该打电话给cell.[your_text_field]

    【讨论】:

    • nameLabel 是我的文本字段的名称,应该澄清
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    相关资源
    最近更新 更多