добавить TestField в новую строку, когда кнопка Touhed Swift - PullRequest
0 голосов
/ 08 ноября 2019

есть табличное представление, и я создаю кнопку во второй ячейке. Я обработал событие Button Touch с протоколом. Я хочу добавить пустое текстовое поле в новую строку в текущем разделе. Точно ниже текстового поля номера телефона, когда нажата кнопка добавления, но я не могу его обработать.

enter image description here

ячейка табличного представления:

protocol InsertTableCellDelegate {
    func insertTableCellDelegate_addrowbtn(sender:InsertTableCell1)
}
class InsertTableCell1: UITableViewCell {

    var delegate : InsertTableCellDelegate?

    @IBOutlet weak var tbCreateRow: UITableView!
    @IBOutlet weak var txtPhoneNumber: JVFloatLabeledTextField!

    override func awakeFromNib() {
        super.awakeFromNib()

    }

    @IBAction func btn_Add_DidTouch(_ sender: Any) {
        if let delegate = self.delegate
        {
            delegate.insertTableCellDelegate_addrowbtn(sender: self)
        }
    }
}

табличное представление Делегаты:

    func numberOfSections(in tableView: UITableView) -> Int {
      return 3
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            if indexPath.section == 0 {
                let cell0 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell0") as! InsertTableCell0

                return cell0
            }else if indexPath.section == 1 {
    //this section should handle add textfield in new row when text button touhed 
                let cell1 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell1") as! InsertTableCell1

                cell1.delegate = self
                return cell1
            }else {
                let cell2 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell2") as! InsertTableCell2
                cell2.txtEmail.text = strEditEmail
                return cell2
            }

    }

//protocol of button : 

       func insertTableCellDelegate_addrowbtn(sender: InsertTableCell1) {
            print("touched")
        }

Ответы [ 2 ]

0 голосов
/ 08 ноября 2019

Пример кода для добавления новой строки при нажатии кнопки добавления в разделе

// Создание выхода для представления таблицы

@IBOutlet weak var currentInsetTableView: UITableView!

// Объявление этих переменных

let reuseInsetCellIdentifier = "insertCell";

let titleSection = ["Add Phone", "Add Email"]
var arrayForCellInSection = Array<Any>()

// Добавить этот код в viewDidLoad ()

currentInsetTableView.delegate = self
currentInsetTableView.dataSource = self

currentInsetTableView.estimatedRowHeight = 200
currentInsetTableView.rowHeight = UITableView.automaticDimension
currentInsetTableView.register(UINib(nibName: "CurrentInsertTableViewCell", bundle: nil), forCellReuseIdentifier: reuseInsetCellIdentifier)

arrayForCellInSection = Array.init(repeating: 1, count: titleSection.count)

// Реализация делегата UITablewView

func numberOfSections(in tableView: UITableView) -> Int {

    return titleSection.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return arrayForCellInSection[section] as! Int
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: reuseInsetCellIdentifier, for: indexPath)
            as! CurrentInsertTableViewCell
            cell.backgroundColor = UIColor.black

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 50
    }

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))
    headerView.backgroundColor = UIColor.black

    let buttonX = 10
    let buttonY = 10
    let buttonWidth = 30
    let buttonHeight = 30

    let button = UIButton(type: .system)
    let imgAdd = UIImage(named: "Add")
    button.setImage(imgAdd, for: .normal)
    button.addTarget(self, action: #selector(buttonClickedForInsertRowInSection(sender:)), for: .touchUpInside)
    button.frame = CGRect(x: buttonX, y: buttonY, width: buttonWidth, height: buttonHeight)
    button.tag = section
    headerView.addSubview(button)

    let label = UILabel()
    label.frame = CGRect.init(x: button.frame.size.width + CGFloat((2 * buttonX)), y: CGFloat(buttonY), width: headerView.frame.width - button.frame.size.width + CGFloat((3 * buttonX)), height: headerView.frame.height - CGFloat((2 * buttonY)))
    label.text = titleSection[section]
    label.textColor = UIColor.white
    headerView.addSubview(label)

    return headerView
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    return 50
}

// CurrentInsertTableViewCell Desing Desing // Окончательный результат: когда мы дважды нажимаем кнопку добавления первого раздела и один раз кнопку добавления второго раздела Result

0 голосов
/ 08 ноября 2019

numberOfRowsInSection имеет фиксированный номер ячейки. Сначала вам нужно создать динамический источник данных.

пример кода:

var dataSource : [Int] = Array.init(repeating: 1, count: 3)

func numberOfSections(in tableView: UITableView) -> Int {

  return dataSource.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
 return dataSource[section]
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.section == 0 {
            let cell0 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell0") as! InsertTableCell0

            return cell0
        }else if indexPath.section == 1 {
//this section should handle add textfield in new row when text button touhed 
            let cell1 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell1") as! InsertTableCell1

            cell1.delegate = self
            return cell1
        }else {
            let cell2 = tableView.dequeueReusableCell(withIdentifier: "InsertTableCell2") as! InsertTableCell2
            cell2.txtEmail.text = strEditEmail
            return cell2
        }

}

// протокол кнопки:

   func insertTableCellDelegate_addrowbtn(sender: InsertTableCell1) {
        dataSource[1] = dataSource[1] + 1
        tableView.reloadData() // or you can use beginUpdates() and endUpdates()
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...