在Swift中刷新

时间:2014-09-29 21:57:41

标签: ios swift

我正在尝试在我的表格视图应用中实现pull to refresh。我一直在寻找人们的例子,我已经知道这几乎是它的要点:

var refreshControl:UIRefreshControl!  

override func viewDidLoad()
{
    super.viewDidLoad()

    self.refreshControl = UIRefreshControl()
    self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
    self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
    self.tableView.addSubview(refreshControl)
}

func refresh(sender:AnyObject)
{
 // Code to refresh table view  
}

然而,我能找到的唯一例子是前一段时间,我知道从那时起语言发生了很大变化!当我尝试使用上面的代码时,我的refreshControl声明旁边出现以下错误:

Cannot override with a stored property 'refresh control'

在阅读其他示例之前我的第一个想法是我必须像这样声明变量:

var refreshControl:UIRefreshControl = UIRefreshControl()

就像我用其他一些变量做的那样,但我猜不是。 任何想法是什么问题?

2 个答案:

答案 0 :(得分:5)

我收集你的班级继承UITableViewControllerUITableViewController已经声明refreshControl属性,如下所示:

@availability(iOS, introduced=6.0)
var refreshControl: UIRefreshControl?

您无需覆盖它。只需删除var声明并分配给继承的属性。

由于继承的属性为Optional,您需要使用?!来解包它:

refreshControl = UIRefreshControl()
refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl!.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
tableView.addSubview(refreshControl!)

答案 1 :(得分:2)

只需在viewDidLoad

中添加此代码即可
self.refreshControl = UIRefreshControl()
        self.refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh")
 self.refreshControl!.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
        self.tableView.addSubview(refreshControl!)

工作正常:)

相关问题