以编程方式将光标放置在自定义 tableView 标题的 textField 中 [英] Programmatically place the Cursor inside a textField of a custom tableView header
问题描述
如何以编程方式确保 tableView-HeaderView-TextField 的光标处于活动状态(即第一响应者)??
How can you programmatically make sure that the cursor of a tableView-HeaderView-TextField gets active (i.e. is the first responder) ??
我的表格看起来像这样(即带有自定义 TextField 标题).到目前为止,光标只能通过在文本字段内部单击来进入灰色标题字段.但我希望能够以编程方式将光标置于文本字段内....
My table looks like this (i.e with the custom TextField header). So far, the cursor only gets inside the grey header field by clicking inside the textfield. But I would like to be able to get the cursor inside the textfield programmatically....
我的自定义 tableview-header 的代码如下所示:
The code for my custom tableview-header looks like this :
// 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 的第一响应者(见代码):
My first approach was to set the first-responder of the headerViewForSection like this (see code):
// reload entries
func reloadEntries() {
self.tableView.reloadData()
// the following does unfortunately not work !!!!!
self.tableView.headerViewForSection(1)?.becomeFirstResponder()
}
不知道为什么这不起作用.也许,Section-Nr (Int=1) 是错误的.但我尝试了几个节号.没有诅咒它应该在哪里.
Not sure why this does not work. Maybe, the Section-Nr (Int=1) is wrong. But I tried several section-numbers. No curser where it should be.
感谢任何帮助!
推荐答案
尝试self.tableView.headerViewForSection(1)?.textfield.becomeFirstResponder()
Try self.tableView.headerViewForSection(1)?.textfield.becomeFirstResponder()
这篇关于以编程方式将光标放置在自定义 tableView 标题的 textField 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!