4

我有一个表格视图,并希望一个部分的标题有一个右对齐的按钮。理想情况下,我可以添加按钮以UITableViewHeaderFooterView获取其标题字体类型、大小和颜色。在我的tableView(tableView: UITableView, viewForHeaderInSection section: Int)我尝试创建一个UIButton并将其添加到UITableViewHeaderFooterView的子视图和内容视图中,但它没有出现。有什么建议么?

4

2 回答 2

2

使用斯威夫特 4。

这会使用 willDisplayHeaderView 委托方法在第一部分的右下角放置一个 UIButton。

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    for subview in view.subviews {
        if subview is UIButton {
           subview.removeFromSuperview()
       }
    }

    if section==0 {
        let button = UIButton(type: UIButtonType.system)
        button.setTitle("Button title", for: .normal)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(button)
        let margins = view.layoutMarginsGuide
        button.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: 0).isActive = true
        button.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: 0).isActive = true
    }
}

@objc func buttonAction(sender: UIButton!) {
  print("Button tapped")
}
于 2020-02-05T10:48:20.000 回答
0

试试这个它对我来说就像一个魅力,

我在 willDisplayHeaderView 委托方法中添加了UIButton ,

1)添加按钮

   - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
    {
      UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
      UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
      [header addSubview:button];
      [button setFrame:CGRectMake(200, -10, 300, 44)];
      [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
      [button.titleLabel setFont:[UIFont fontWithName:@"Helvetica" size:35]];
      [button setTitle:@"Add" forState:UIControlStateNormal];
      [button addTarget:self action:@selector(addbuttonclicked) forControlEvents:UIControlEventTouchUpInside]; }

2)添加按钮动作

  -(void)addbuttonclicked
   {
     //Add code     
   }

希望这对某人有帮助。

于 2016-12-28T13:33:05.227 回答