如何在Swift中将数据源作为字符串?

时间:2015-03-01 22:22:39

标签: uitableview swift ios8 xcode6

我正在使用UITableView,因此使用UITableViewDataSource。我的dataSource是

        theTableView.dataSource = self

但是我想让UITableView从名为'phone'的变量中获取数据,这是一个String。当前错误为“String与UITableViewDataSource不同”。

如何让UITableView从字符串变量中获取数据?

谢谢 - 希望这最终也会对其他人有用。

(对于那些寻找相同解决方案的其他人来说无关紧要:var'phone'是通过Contacts框架从用户的联系人中提取的电话号码。我正在尝试让UITableView接收新的电话号码每次他们被选中)。

1 个答案:

答案 0 :(得分:0)

好吧,您需要将tableView的数据源设置为符合UITableViewDataSource协议的类。然后定义tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath)函数。

示例:

import Foundation

class Example : UITableView, UITableViewDataSource, UITableViewDelegate
{
    var dataSource = [ "hello", "how", "are", "you" ]

    // MARK: Lifecycle
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)

    }

    override init(frame: CGRect) {

        super.init(frame: frame)

        self.dataSource = self
        self.delegate = self
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    // MARK: Data Source / Delegates
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cellId")

        cell.textLabel?.text = self.dataSource[indexPath.row]

        return cell
    }
}
相关问题