Swift TableView вставки строки под кнопкой нажал - PullRequest
0 голосов
/ 13 апреля 2020

Я новичок в Swift и использую Swift 4.2. У меня есть TableView с меткой и кнопкой. Когда я нажимаю кнопку, я хочу добавить новую строку прямо под строкой, в которой была нажата кнопка. Прямо сейчас, когда я нажимаю кнопку, новая строка добавляется в нижнюю часть TableView каждый раз. Я просматривал посты здесь, но не смог заставить его работать, это моя база кода. У меня есть метод с именем RowClick Я получаю путь индекса строки, по которой щелкнули, но не знаю, как ее использовать, чтобы новая строка отображалась непосредственно под строкой, по которой щелкнули.

class ExpandController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var TableSource: UITableView!


    var videos: [String] = ["FaceBook","Twitter","Instagram"]

    override func viewDidLoad() {
        super.viewDidLoad()
        TableSource.delegate = self
        TableSource.dataSource = self
        TableSource.tableFooterView = UIView(frame: CGRect.zero)
        // Do any additional setup after loading the view.
    }



    @IBAction func RowClick(_ sender: UIButton) {
        guard let cell = sender.superview?.superview as? ExpandTVC else {
            return
        }

        let indexPath = TableSource.indexPath(for: cell)
        InsertVideoTitle(indexPath: indexPath)
    }
    func InsertVideoTitle(indexPath: IndexPath?)
    {
        videos.append("Snapchat")
        let indexPath = IndexPath(row: videos.count - 1, section: 0)
        TableSource.beginUpdates()
        TableSource.insertRows(at: [indexPath], with: .automatic)
        TableSource.endUpdates()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return videos.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let videoTitle = videos[indexPath.row]
        let cell = TableSource.dequeueReusableCell(withIdentifier: "ExpandTVC") as! ExpandTVC
        cell.Title.text = videoTitle

        cell.ButtonRow.tag = indexPath.row
        cell.ButtonRow.setTitle("Rows",for: .normal)

        return cell
    }

}

Вот так выглядит моя таблица. Я нажал кнопку «Строки Facebook», и к ней добавилась строка Snapchat. Вместо этого ярлык Snapchat должен появиться в строке ниже Facebook. Любые предложения будут великолепны!

enter image description here

Ответы [ 2 ]

1 голос
/ 13 апреля 2020

Я думаю, что самым простым решением без переписывания всего этого было бы добавление 1 к текущей строке IndexPath, которую вы захватили из действия.

let indexPath = TableSource.indexPath(for: cell)
        var newIndexPath = indexPath;
        newIndexPath.row += 1;
        InsertVideoTitle(indexPath: newIndexPath);

Я сделал это из памяти, потому что я не рядом с IDE, так что посмотрите на изменение и примените это изменение в случае необходимости в любом другом месте.

class ExpandController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var TableSource: UITableView!


    var videos: [String] = ["FaceBook","Twitter","Instagram"]

    override func viewDidLoad() {
        super.viewDidLoad()
        TableSource.delegate = self
        TableSource.dataSource = self
        TableSource.tableFooterView = UIView(frame: CGRect.zero)
        // Do any additional setup after loading the view.
    }



    @IBAction func RowClick(_ sender: UIButton) {
        guard let cell = sender.superview?.superview as? ExpandTVC else {
            return
        }

        let indexPath = TableSource.indexPath(for: cell)
        var newIndexPath = indexPath;
        newIndexPath.row += 1;
        InsertVideoTitle(indexPath: newIndexPath);
    }
    func InsertVideoTitle(indexPath: IndexPath?)
    {
        videos.append("Snapchat")
        let indexPath = IndexPath(row: videos.count - 1, section: 0)
        TableSource.beginUpdates()
        TableSource.insertRows(at: [indexPath], with: .automatic)
        TableSource.endUpdates()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return videos.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let videoTitle = videos[indexPath.row]
        let cell = TableSource.dequeueReusableCell(withIdentifier: "ExpandTVC") as! ExpandTVC
        cell.Title.text = videoTitle

        cell.ButtonRow.tag = indexPath.row
        cell.ButtonRow.setTitle("Rows",for: .normal)

        return cell
    }

}
0 голосов
/ 13 апреля 2020

Ваш текущий код вызывает append, чтобы добавить новый элемент в конец массива. Что вы хотите сделать, это вставить новую строку в indexPath.row+1. Array имеет функцию insert(element,at:).

Вы должны обработать случай, когда пользователь коснулся последней строки и не добавлять 1, чтобы избежать ошибки границ массива:

func InsertVideoTitle(indexPath: IndexPath)
{
    let targetRow = indexPath.row < videos.endIndex ? indexPath.row+1 : indexPath.row 
    videos.insert("Snapchat" at:targetRow)
    let newIndexPath = IndexPath(row: targetRow, section: 0)
    TableSource.beginUpdates()
    TableSource.insertRows(at: [newIndexPath], with: .automatic)
    TableSource.endUpdates()
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...