将添加按钮放入UITableView标题(swift)

mzaanser  于 11个月前  发布在  Swift
关注(0)|答案(1)|浏览(73)

我使用viewForHeaderInSection放置添加按钮,如下所示:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let frame: CGRect = tableView.frame
    let addButton: UIButton = UIButton(frame: CGRectMake(70, 0, 70, 70))
    addButton.setTitle("+", for: .normal)
    addButton.layer.cornerRadius = 8

    addButton.backgroundColor = .blue
    let headerView: UIView = UIView(frame: CGRectMake(0, 0, frame.size.height, frame.size.width))
    headerView.addSubview(addButton)
    addButton.addConstraints(.alignTrailingWithTrailing(of: headerView, const: 10))
    return headerView
}

不幸的是,这使得我的UITable视图看起来不太好:

如何将添加按钮放置到标题部分?(“联系人”标题的权利)。
谢谢。视图层次结构已附加。

hk8txs48

hk8txs481#

似乎没有办法在UITableViewController中实现它。
但还有另一种方法-您可以创建UIViewController,使其符合TableView协议,并使用添加按钮实现UITableView和UIView。
我是这样做的:

final class ContactsController: UIViewController, UITableViewDelegate, UITableViewDataSource {

   lazy var addButton = { [view = self.buttonBarView] in
    let button = UIButton()
    view.addSubview(button)
    button.layer.cornerRadius = 8
    button.backgroundColor = .systemBlue
    button.setTitle("+", for: .normal)
    button.addConstraints(
        .alignTopWithTop(of: view),
        .alignBottomWithBottom(of: view),
        .alignTrailingWithTrailing(of: view, const: 8),
        .setAspectWidth(ratio: 1)
    )
    return button
}()

lazy var buttonBarView = { [view = self.view] in
    let barView = UIView()
    if let view {
        view.addSubview(barView)
        barView.addConstraints(
            .alignTopWithTop(of: view),
            .alignLeadingWithLeading(of: view),
            .alignWidth(with: view, mult: 1),
            .alignHeight(with: view, mult: 0.045)
        )
    }
    return barView
}()

lazy var tableView = { [view = self.view, buttonBarView = self.buttonBarView] in
    let tableView = UITableView()
    if let view {
        self.view.addSubview(tableView)
        tableView.addConstraints(
            .alignTopWithBottom(of: buttonBarView),
            .alignLeadingWithLeading(of: view),
            .alignWidth(with: view, mult: 1),
            .alignBottomWithBottom(of: view)
        )
    }
    return tableView
}()

// UITableViewDelegate and UITableViewDataSource stuff here..

它按预期工作:

相关问题