Как создать подкласс SwipeTableViewController, если я уже создаю подкласс UIViewController? Кроме того, как отобразить клавиатуру для пользователя? (Swift) - PullRequest
0 голосов
/ 02 декабря 2019

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

Итак, я хорошо знаю, что класс не может создавать подклассы более одного раза, поэтому как мне перейти к созданию подклассов Cocoapod SwipeTableViewController, а также CollapsableTableViewController, если я уже создаю подкласс UIViewController?

Мой второй вопрос: почему клавиатура не отображается, когда я нажимаю на текстовое поле, чтобы назвать свою тренировку? Я пытался использовать textField.becomeFirstResponder (), но это ничего не сделало для меня. Какие-либо предложения? У меня также есть окно выбора в том же виде, что и текстовое поле, может ли это иметь какое-то отношение к моей проблеме?

Любая помощь будет высоко ценится!

import UIKit
import RealmSwift
import SwipeCellKit
import CollapsibleTableSectionViewController


class WorkoutsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SwipeTableViewCellDelegate, CollapsibleTableSectionDelegate {


    let realm = try! Realm()

    var workouts : Results<Workouts>?
    var days : Results<WeekDays>!

    var daysOfWeek : [String] = ["Monday", "Tuesday", "Wednsday", "Thursday", "Friday", "Saturday", "Sunday"]

    let picker = UIPickerView()


    @IBOutlet weak var WorkoutsTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        WorkoutsTableView.delegate = self
        WorkoutsTableView.dataSource = self


        print(Realm.Configuration.defaultConfiguration.fileURL)

        picker.delegate = self
        picker.dataSource = self

        loadCategories()

    }


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

        tableView.rowHeight = 80.0

        //Populate based on the # of workouts in each day.

        let day = days[section]
        return day.workouts.count
    }


    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return days[section].day
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return days.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SwipeTableViewCell

        cell.delegate = self

        if (days?[indexPath.row]) != nil {
            cell.accessoryType = .disclosureIndicator
            //Populate with titles of workouts based on section/day of the week.
            //cell.textLabel?.text = days?[indexPath.row].workouts[indexPath.row].name
            cell.textLabel?.text = days[indexPath.section].workouts[indexPath.row].name
        }
        return cell
    }

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {

        guard orientation == .right else { return nil }

        let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in

            self.updateModel(at: indexPath)
        }
        // customize the action appearance
        deleteAction.image = UIImage(named: "delete-icon")

        return [deleteAction]
    }

    func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
        var options = SwipeOptions()
        options.expansionStyle = .destructive
        return options
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }



    @IBAction func AddWorkoutButton(_ sender: UIButton) {
        var textField = UITextField()

        let alert = UIAlertController(title: "New Workout", message: "Please name your workout...", preferredStyle: .alert)

        let addAction = UIAlertAction(title: "Add Workout", style: .default) { (UIAlertAction) in
                //Add workout to database
                //Create a two dimensional array object in Realm with numbers corresponding to each day of the week.
                //Append workouts to the day in the dictionary that the user selects.
            let newWorkout = Workouts()
            let dow = WeekDays()
            dow.day = self.daysOfWeek[self.picker.selectedRow(inComponent: 0)]
            newWorkout.name = textField.text!
            dow.workouts.append(newWorkout)

            self.save(newDay: dow)
        }

        alert.addTextField { (alertTextField) in
            alertTextField.placeholder = "Muscle Group"
            textField = alertTextField
            alertTextField.inputView = self.picker
        }

        alert.addAction(addAction)

        present(alert, animated: true, completion: nil)
    }

    func save(newDay: WeekDays){
        do {
            try realm.write {
                realm.add(newDay)
            }
        } catch {
            print("Error saving workout \(error)")
        }
        WorkoutsTableView.reloadData()
    }

    func updateModel(at indexPath: IndexPath){
        if let workoutForDeletion = self.days?[indexPath.row]{
            do {
                try self.realm.write {
                    self.realm.delete(workoutForDeletion)
                }
            } catch {
                print("Error deleting workout, \(error)")
            }
        }
        WorkoutsTableView.reloadData()
    }

    func loadCategories(){
        days = realm.objects(WeekDays.self)
        WorkoutsTableView.reloadData()
    }

    @IBAction func EditWorkout(_ sender: UIBarButtonItem) {

    }

}

extension WorkoutsViewController : UIPickerViewDelegate, UIPickerViewDataSource {

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 7
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return daysOfWeek[row]
    }
}

1 Ответ

1 голос
/ 02 декабря 2019

Что касается вашего первого вопроса, я не думаю, что вам нужно волноваться.

Вы должны унаследовать от CollapsibleTableSectionViewController, если это то, что вы хотите использовать. Это само по себе расширяет UIViewController, поэтому вам не нужно делать это самостоятельно.

Я не вижу никаких SwipeTableViewController в SwipeCellKit - вам просто нужно где-то реализовать делегат (в коде вашего основного представления все в порядке), и вы можете «наследовать»(на самом деле, «реализовать»), так как это протокол, , а не класс (посмотрите на разницу между классами и протоколами, чтобы выяснить, почему).

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

...