Swift:将类数组中的变量引用到UITableView的字符串中

时间:2015-05-21 05:19:51

标签: swift

我正在尝试创建我的第一个应用程序(耶!)并需要一些帮助。 我正在尝试创建一个名为Medication的自定义类,我可以在其中存储有关某种药物的信息,并提供一个供人选择的药物列表(在表格视图中)。 我创建了我的新课程Medication:

class Medication: NSObject {
var name: String
var bottleColor: UIColor
var usage: String
var patientMed: Bool = false
var eye: String

init(name: String, bottleColor:UIColor, usage:String, eye: String, patientMed:Bool) {
self.name = name
self.bottleColor = bottleColor
self.usage = usage
self.patientMed = patientMed
self.eye = eye 
}
}

我创建了一个变量来存储Medication数组:

var fullMedsList = [Medication]()

我创建了一个将数据附加到数组中的函数,但是当我尝试将其引用到表视图中时,我无法弄清楚如何提取适当的数据。 这是我的代码和我无法弄清楚的区域:

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
    return self.myMedsList.count;
}

func tableView(tableView: UITableView!,
cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{

let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")
cell.textLabel!.text = myMedsList.name[indexPath.row]

return cell
}

我收到错误说((Medication))在这一行没有名为'name'的成员:     cell.textLabel!.text = myMedsList.name [indexPath.row] 问题是,如何将我的Medication类中的名称数据引用到tableview中?理想情况下,我想引用Medication.name并有一个Medication.usage的副标题,但我只是想先了解基础知识! 我很感激你的帮助r / swift!

2 个答案:

答案 0 :(得分:1)

问题在于     indexPath.row,您试图在名为name的数组中获取indexPath.row元素。 但这不是您想要的:以myMedList的方式获取cell.textLabel!.text = myMedsList[indexPath.row].name 索引的名称:

public test(){
    Home home = ...//call the constructor of home to create an instance
    if(null!=home && home.mName=="xxx") {// bad comparison of string and bad way to access an instance variable
        //some code
    }
}

答案 1 :(得分:0)

您的名字不是数组。它是一个字符串。这样做

func tableView(tableView: UITableView!,
cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{

let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")
let med = myMedsList[indexPath.row]
cell.textLabel!.text = med.name
cell.detailLabel.text = med.usage

return cell
}
相关问题