我想制作一个包含不同人的表格 View 。您可以通过单击添加按钮来添加人员。当您单击添加按钮时,您将填写信息“名字”、“姓氏”和“日期”。当您单击完成按钮时,它会返回到表格 View 并且单元格会显示此人的名字。
我创建了一个新的 swift 文件,它有一个结构:
struct person {
var firstName : String
var lastName : String
var date : String
}
在 tabledetailviewcontroller.swift(添加人员的 Controller )中,我为每个字段声明 IBOutlets 并设置每个值:
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var dateText: UITextField!
let first:String = ""
let last:String = ""
let date = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .ShortStyle)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "doneSegue" {
first = firstName.text
last = lastName.text
date = dateText.text
}
}
在 tableviewcontroller.swift 中,我声明了一组类型为“person”的人:
var people = [person]()
和一个返回数组中人数的函数。
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
然后我有一个函数可以设置单元格的文本值 覆盖 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("issueCell", forIndexPath: indexPath) as UITableViewCell
//cell.textLabel.text = issues.dateTime[indexPath.row] //Fixed this to this =>
cell.textLabel.text = (issues[indexPath.row]).dateTime
return cell
}
最后我有一个完成按钮将新人附加到数组(这部分一直给我错误...)
@IBAction func done(segue:UIStoryboardSegue){
var addPersonVC = segue.sourceViewController as AddPersonViewController
let newPerson = person(date: (addPersonVC.date)) //Breaks here for no reason!
people.append(newPerson)
}
我的问题是,如何让每个单元格存储多个字段(名字、姓氏、日期),将其保存在每个人的下方,并让该人的姓名显示在表格 View 的单元格中?我希望能够编辑单元格并更改有关该人的信息。
我对 swift 还很陌生:/ 非常感谢!
编辑:我已经修复了一些问题,现在它在 done 函数处中断了!
最佳答案
如果我没记错或遗漏了一些代码,那么你有两个错误:
- 您的结构称为“person”(小 p),但您使用 Person(date: (addPersonVC.date)) 实例化了新的 Person
- 如果你的结构的属性是用 let 声明的,你需要在初始化中定义它们,因为它们是常量。否则你必须称他们为 var
关于ios - 如何在具有多个字段的 TableView 中创建一个单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27002537/