ios - 在 TableView 中显示结构数组

标签 ios swift uitableview

我正在编写一个任务应用程序,并尝试收集用户的输入,并使用它来显示更新后的 UITableView 以及用户创建的任务。

我的问题是:

  1. 用户任务列表未正确追加(每次添加任务时,数组的内容并未追加,而是被替换。
  2. taskTable UITableView 没有正确显示任务结构数组的内容。

TaskManager.swift 类接收任务详细信息并将任务结构添加到数组中。

import UIKit

struct task{
var name: String
var desc: String
var due_date: String

init(name: String, desc: String, due_date: String)
{
    self.name = name
    self.desc = desc
    self.due_date = due_date
}
}

var TaskMgr: TaskManager = TaskManager()


class TaskManager: UIViewController {
var tasks = [task]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/*
 *   Purpose: Add new task to task array
 *   Parameters: task (struct) to add
 *   Return: n/a
 */
func addTask(name: String, desc: String, due_date: String) {
    print("got to add task method")
    tasks.append(task(name: name, desc: desc, due_date: due_date))

    print("value of tasks[0] is:",tasks[0])
    print("number of elements in array: ",tasks.count)
    //the task array count should increase as the user adds more tasks,
    //but from this code, it is replacing elements 
    //(only saying there is one element, the most recently added one)

}

这是 FirstViewController.swift 类,从新任务屏幕读取输入,并将其发送到 TaskManager 类以添加到任务列表。

import UIKit

//display task class
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var taskTable: UITableView!

@IBOutlet weak var taskName_txt: UITextField!
@IBOutlet weak var taskDesc_txt: UITextField!
@IBOutlet weak var taskDueDate_txt: UIDatePicker!
@IBOutlet weak var taskDone_btn: UIBarButtonItem!
@IBOutlet weak var addTask_btn: UIBarButtonItem!

var activeTextField = UITextField()


//Cancel task button function
@IBAction func cancelTask_btn(_ sender: Any) {
    performSegue(withIdentifier: "backToTasks_seg", sender: cancelTask_btn)
}


override func viewDidLoad() {
    super.viewDidLoad()
    //taskTable.reloadData()
    //taskTable.reloadData()

}

@IBAction func addTaskPressed(_ sender: Any) {
    performSegue(withIdentifier: "addTask_seg", sender: taskDone_btn)
}

func textFieldDidBeginEditing(textField: UITextField) {

    self.activeTextField = textField
    activeTextField.backgroundColor = UIColor(red: 187.00, green: 128.00, blue: 74.00, alpha: 1.00)
}


/*
 *   Purpose: Triggered off user 'Done' button click
        Creates a task to add
 *   Parameters: button clicked
 *   Return: n/a
 */
@IBAction func doneTaskInput_btn(_ sender: Any) {
    print("Done task input button pressed")

    //if user input is valid, create a task from data they input
    //return back to task table screen
    if(isInputValid() != false){

        let name = taskName_txt.text!
        print("Task name is: ",name)
        let desc = taskDesc_txt.text!
        print("Task desc is: ",desc)

        let due_date = handler(sender: taskDueDate_txt)
        print("Task due date is: ",due_date)
        print("Adding task to task list...")


        TaskManager().addTask(name: name, desc: desc, due_date: due_date)


    }//end check isValid

    //added task to array, now go back to task table to display tasks
    performSegue(withIdentifier: "backToTasks_seg", sender: taskDone_btn)


}//end function


/*
*   Purpose: checks if user entered a task name
*   Parameters: none
*   Return: true if user entered task name
        false otherwise
*/
func isInputValid()-> Bool{

    var taskName: String?

    if taskName != ""{
        taskName = taskName_txt.text
        return true
    }else{
        taskName_txt.backgroundColor = UIColor.red
        taskName_txt.placeholder = "Add a task name"
        return false
    }

}//end isInputValid method

/*
 *   Purpose: Parses date from UIDatePicker to string
 *   Parameters: DatePicker to read date from
 *   Return: formatted string date
 */
func handler(sender: UIDatePicker)->String {

    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "dd-MM-yyyy HH:mm"

    let strDate = timeFormatter.string(from: taskDueDate_txt.date)

    return strDate
}//end handler method


/*
 *   Purpose: Remove cell
 *   Parameters: task table, edit value
 *   Return: n/a
 */
func tableView(taskTable: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
    if (editingStyle == UITableViewCellEditingStyle.delete){

        TaskMgr.tasks.remove(at: indexPath.row)
        taskTable.reloadData()
    }
}

/*
 *   Purpose: Returns number of sections (columns) in table
 *   Parameters: table
 *   Return: number of sections (colums)
 */
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    print( "setting number of sections");
    return 1
}



/*
 *   Purpose: Returns number of rows in array to the table view
 *   Parameters: taskTable, number of rows
 *   Return: number of rows (int)
 */
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return TaskMgr.tasks.count // taskList.count
}

/*
 *   Purpose: Populate cells with data from array of task structs
 *   Parameters: task table, row to insert data
 *   Return: populated cell
 */
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: UITableViewCell = UITableViewCell(style:     UITableViewCellStyle.subtitle, reuseIdentifier: "Default Tasks")
    cell.textLabel?.text = TaskMgr.tasks[indexPath.row].name
    cell.detailTextLabel!.text = TaskMgr.tasks[indexPath.row].desc

    return cell
}

}

感谢您的帮助!

最佳答案

每次您转到任务管理器 View Controller 时,我都有一种感觉,它是一个新实例?

var tasks = [task]()

这也可以重置它吗? 我会尝试将任务数组放在 FirstViewController 中,然后您可以直接访问其中的结构。

关于ios - 在 TableView 中显示结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43553431/

相关文章:

ios - 获取Facebook用户 friend 的生日

objective-c - 使 UITableView 的第一个单元格与其他每个单元格不同

ios - Tableview 在选择上传递相同的数据

ios - 如何进一步缩短三元运算符

ios - 如何使用自定义对象中的单个字段填充 TableView?

ios - -(void)updateConstraints 中的动画约束变化

ios public static const 等价物

objective-c - UIImageJPEGRepresentation 在每个 iOS 设备上的行为是否应该相同?

ios - Socket.io监听方法在一段时间或失去Internet连接后不监听

ios - Swift 中泛型类型的工厂(协议(protocol)和泛型)