如何在表格视图的某个部分的页脚中添加按钮?

时间:2017-06-06 23:37:22

标签: ios swift uitableview

我想在我的表格视图的页脚中添加一个按钮(或者至少使整个内容可以点击)。我该怎么做呢?提前谢谢!

1 个答案:

答案 0 :(得分:3)

Apple's Docs你必须实现heightForFooterInSection方法,否则你的viewForFooterInSection将不会做任何事情。

Swift 3

override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 100
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {

guard section == 0 else { return nil } // Can remove if want button for all sections

let footerView = UIView(frame: CGRect(0, 0, 320, 40))
        let myButton = UIButton(type: .custom)

        myButton.setTitle("My Button", for: .normal)
        myButton.addTarget(self, action: #selector(myAction(_:)), for: .touchUpInside)

        myButton.setTitleColor(UIColor.black, for: .normal) //set the color this is may be different for iOS 7
        myButton.frame = CGRect(0, 0, 130, 30) //set some large width to ur title
        footerView.addSubview(myButton)
        return footerView;

}

func myAction(_ sender : AnyObject) {

}

<强>目标C

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
      return 100.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(section == 0) //Decide which footer according to your logic 
    {
       UIView *footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
       UIButton *myButton=[UIButton buttonWithType:UIButtonTypeCustom];
       [myButton setTitle:@"Add to other" forState:UIControlStateNormal];
       [myButton addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
       [myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//set the color this is may be different for iOS 7
       myButton.frame=CGRectMake(0, 0, 130, 30); //set some large width to ur title 
       [footerView addSubview: myButton];
       return footerView;
    }
}

- (void)myAction:(id)sender
{
      NSLog(@"add to charity");
}