首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以编程方式将光标放在自定义tableView标头的textField内

以编程方式将光标放在自定义tableView标头的textField内
EN

Stack Overflow用户
提问于 2015-05-26 04:49:54
回答 2查看 619关注 0票数 0

如何以编程方式确保tableView-HeaderView-TextField的光标激活(即是第一响应器)?

我的表格看起来像这样(即带有自定义的TextField标题)。到目前为止,光标只能通过在文本字段内单击来进入灰色标题字段。但我希望能够以编程方式将光标放入文本字段中。

我的自定义tableview-header代码如下所示:

代码语言:javascript
复制
// drawing a custom Header-View with a TextField on top of the tableView
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let container = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
    let textField = UITextField(frame: CGRectMake(10, 15, self.view.frame.size.width/2 - 40, 45))
    textField.delegate = self
    self.txtfield = textField
    textField.textColor = UIColor.blackColor()
    let placeholder = NSAttributedString(string: "..add player", attributes: [NSForegroundColorAttributeName: UIColor.darkGrayColor()])
    textField.attributedPlaceholder = placeholder
    textField.backgroundColor = UIColor.lightGrayColor()
    container.addSubview(textField)

    var headPlusBttn:UIButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as! UIButton
    headPlusBttn.center.x = self.view.frame.size.width - 20
    headPlusBttn.center.y = 38
    headPlusBttn.enabled = true
    headPlusBttn.addTarget(self, action: "addTeam:", forControlEvents: UIControlEvents.TouchUpInside)
    container.addSubview(headPlusBttn)

    return container
}

我的第一种方法是这样设置headerViewForSection的first-responder (参见代码):

代码语言:javascript
复制
// reload entries
func reloadEntries() {
    self.tableView.reloadData()
    // the following does unfortunately not work !!!!!
    self.tableView.headerViewForSection(1)?.becomeFirstResponder()
}

不确定为什么这不起作用。也许,Section (Int=1)是错误的。但我试了几个区号。没有诅咒在它应该在的地方。

感谢任何人的帮助!

EN

回答 2

Stack Overflow用户

发布于 2015-05-26 06:07:27

通常,在这样的情况下,添加延迟会有所帮助。它允许操作系统对视图做任何它想做的事情,这样就不会在同一时间搞乱你想要做的事情。

可能是这样的:

代码语言:javascript
复制
func reloadEntries() {
    self.tableView.reloadData()

    let delay = (Int64(NSEC_PER_SEC) * 0.1)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
        self.tableView.headerViewForSection(1)?.becomeFirstResponder()
    })
}

我还没有测试它来做你想要做的事情,所以你可能需要找一个不同的地方来放置它。

另外,您确定要影响第1节中的视图吗?从您的图像看,您似乎想要打乱第0节中的标题。

一定要进入调试器并检查头文件是否为空。您的代码暗示这是一个有效的条件。你可以试着这样写(至少为了测试):

代码语言:javascript
复制
if let header = self.tableView.headerViewForSection(1) {
    header.becomeFirstResponder()
}
else {
    print("There is no header.")
}
票数 0
EN

Stack Overflow用户

发布于 2015-05-26 06:29:36

试试self.tableView.headerViewForSection(1)?.textfield.becomeFirstResponder()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30445823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档