ios - 以编程方式将按钮对齐到 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
}
}
解决方案
添加以下代码以使应用约束有效
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
推荐阅读
- c++ - 递归函数中的return语句
- swift - SwiftUI 无法创建导航视图
- android - 我将为此 StoreBuilder 使用什么样的密钥
- c# - CsvWriter,CS1503 参数 2:无法转换 CultureInfo
- r - R中同名data.frame的子集
- javascript - 错误:函数组件不能有引用。你的意思是使用 React.forwardRef() 吗?
- c - 从 Rust 进行 FFI 时如何处理 C 宏?
- reactjs - 无论如何使用 npm start 从前缀 URL(例如 /client/static)提供 /static?
- firebase - Firebase 动态链接在运行 iOS13.3 的设备上无法正常工作,但在模拟器 (iOS13.2) 和运行 iOS12 的 iPhone 上正常工作
- javascript - 然后阻止中的意外令牌