将工具栏添加到tableview的底部

时间:2014-12-24 13:58:41

标签: ios swift toolbar

我试图在tableViewController的底部添加一个工具栏。当我使用这段代码时:

override func viewDidLoad() {
    let toolbar: UIToolbar = UIToolbar()
    let checkButton = [UIBarButtonItem]()
    toolbar.frame = CGRectMake(0, self.view.frame.size.height - 46, self.view.frame.size.width, 48)
    toolbar.sizeToFit()
    toolbar.setItems(checkButton, animated: true)
    toolbar.backgroundColor = UIColor.redColor()
    self.view.addSubview(toolbar)
}

我得到了这个结果:

enter image description here

我的问题是: 1)为什么工具栏透明? 2)为什么没有条形按钮?

有关如何继续的任何建议将不胜感激。

编辑:

我现在已将代码更改为以下内容:

func checkedPress(){

    println("saywhat")

}

override func viewDidLoad() {
    let toolbar: UIToolbar = UIToolbar()
    let checkButton = [UIBarButtonItem(title: "Done", style: .Done, target: self, action: "checkedPress")]
    toolbar.frame = CGRectMake(0, self.view.frame.size.height - 46, self.view.frame.size.width, 48)
    toolbar.sizeToFit()
    toolbar.setItems(checkButton, animated: true)
    toolbar.backgroundColor = UIColor.redColor()
    self.view.addSubview(toolbar)
}

并且它有效,尽管有这个bug: enter image description here

正如您所看到的,工具栏在滚动时会跟随表格的其余部分,这不应该发生。

同样,任何建议都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

由于UITableView继承自UIScrollView,您需要覆盖scrollViewDidScrollMethod方法。

在课堂上,您可以使用此代码。

var toolbar: UIToolbar = UIToolbar()

override func viewDidLoad() {
    let checkButton = [UIBarButtonItem]()
    toolbar.frame = CGRectMake(0, self.view.frame.size.height - 46, self.view.frame.size.width, 48)
    toolbar.sizeToFit()
    toolbar.setItems(checkButton, animated: true)
    toolbar.backgroundColor = UIColor.redColor()
    self.view.addSubview(toolbar)
}

override func scrollViewDidScroll(scrollView: UIScrollView) {
    var frame:CGRect = self.toolbar.frame
    frame.origin.y =  scrollView.contentOffset.y + self.tableView.frame.size.height - self.toolbar.frame.size.height
    self.toolbar.frame = frame

    self.view .bringSubviewToFront(self.toolbar)

}

`