将UITextfield添加为单元格的附件视图

时间:2015-04-04 22:57:40

标签: uitableview swift ios8 uitextfield

我的tableView中有4个部分,每个部分都有单个单元格。当用户选择第四部分的单元格时,我希望他们在其上键入。所以我在didSelectRow函数中添加了textfield作为该单元格的accessoryView,如下所示。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    if indexPath.section == 3 {

            //adding textField
            theTextField = UITextField(frame: CGRectMake(10, 480, 300, 40))
            theTextField.backgroundColor = UIColor.brownColor()
            theTextField.placeholder = "Please type here...."
            theTextField.textColor = UIColor.yellowColor()
            theTextField.layer.cornerRadius = 10.0
            selectedCell?.accessoryView = theTextField   
        }

但是当我点击它时,键盘隐藏了那个单元格。我希望表视图向上滚动。请帮我解决这个问题,如果还有其他方法可以帮助我,请告诉我!

This is when I select the fourth cell

Table View Look like this

1 个答案:

答案 0 :(得分:0)

当“更多逻辑位置”位于“cellForRowAtIndexPath”中时,不清楚为什么要在“didSelectRowAtIndexPath”中实现单元格规范。我实现了你的代码,除了在cellForRowAtIndexPath中放入第3节的单元格规格,表格单元格按预期向上滚动。见下面的代码。要利用tableview滚动,需要在cellRowForIndex中定义单元格。为了满足评论中所述的目标,您可以使用.hidden功能并插入代码,如图所示。

import UIKit

class:UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.section == 3 {
        selectedCell.accessoryView?.backgroundColor = UIColor.brownColor()
        selectedCell.accessoryView?.hidden = false
    } else {
        selectedCell.accessoryView?.hidden = true
    }

}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
   return 4
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
    if indexPath.section == 3 {

        //adding textField
        var theTextField = UITextField(frame: CGRectMake(10, 480, 300, 40))
        theTextField.backgroundColor = UIColor.brownColor()
        theTextField.placeholder = "Please type here...."
        theTextField.textColor = UIColor.yellowColor()
        theTextField.layer.cornerRadius = 10.0
        cell.accessoryView = theTextField
        cell.accessoryView?.hidden = true
    }

    else {
        cell.textLabel!.text = "\(indexPath.section)"
    }

    return cell
}

}

Simulator running 4S