首页 > 解决方案 > 以编程方式将按钮对齐到 UITableView 单元格的左侧

问题描述

我正在使用 Swift 5、Xcode 11 和 ui 表视图控制器创建一个简单的应用程序。在 ui 表视图中,我想要 2 个按钮:我的表视图左侧的一个按钮,右侧的另一个。我尝试了许多其他相关/类似问题的答案,但都失败了(可能是因为 1. 太旧,2. 用 OBJ-C 编写的答案)。

这是我的表视图控制器:


import UIKit

@objcMembers class CustomViewController: UITableViewController {

    var tag = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    // 3
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        tag = tag + 1

        let cell = tableView.dequeueReusableCell(withIdentifier: "themeCell", for: indexPath) as! ThemeCell
        var cellButton: UIButton!


        cellButton = UIButton(frame: CGRect(x: 5, y: 5, width: 50, height: 30))
        cell.addSubview(cellButton)
        cell.img.image = UIImage(named: SingletonViewController.themes[indexPath.row])
        cell.accessoryView = cellButton
        cellButton.backgroundColor = UIColor.red
        cellButton.tag = tag
        return cell
    }

}

这是我目前得到的: IMG

标签: iosswiftxcodeuitableviewuicollectionview

解决方案


添加以下代码以使应用约束有效

let cellButton = UIButton(frame: CGRect.zero)
cellButton.translatesAutoresizingMaskIntoConstraints = false
cell.addSubview(cellButton)
cell.accessoryView = cellButton
cellButton.backgroundColor = UIColor.red

cellButton.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 5).isActive = true
cellButton.topAnchor.constraint(equalTo: cell.topAnchor, constant: 5).isActive = true
cellButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
cellButton.heightAnchor.constraint(equalToConstant: 30).isActive = true

推荐阅读