作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Xcode 和 Swift 5 创建一个简单的 iOS 应用程序,用户可以在其中选择一个主题,然后背景会改变颜色。我想通过在表格 View 的单元格上添加按钮来实现这一点。我知道如何将一个按钮添加到表格 View ,但我不知道如何将多个按钮放入表格 View 单元格。
这是一个表格 View 单元格,其中添加了一个按钮:
ps:忽略按钮内的文字
我想要的是每边一个按钮,中间一个按钮,如下所示:
这是我的 TableView Controller :
import UIKit
@objcMembers class TBController: UITableViewController {
var times = 0
var lastChar = ""
var subString = ""
var text = ""
override func viewDidLoad() {
super.viewDidLoad()
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
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 singleton.count
}
// 3
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var cellButton: UIButton!
///////////////////
cellButton = UIButton(frame: CGRect(x: 5, y: 5, width: 50, height: 30))//5, 5, 50, 30
times = times + 1
cell.textLabel?.text = SingletonViewController.singleton[indexPath.row]
if times == 1{
cellButton.setTitle("Back", for: UIControl.State.normal)
cell.addSubview(cellButton)
cell.accessoryView = cellButton
cellButton.backgroundColor = UIColor.blue
cell.tag = 1
}else{
cell.tag = 2
}
return cell
}
}
最佳答案
您需要子类 UITableViewCell
并创建您自己的自定义实现,您可以通过代码或 IB 执行此操作
这是 IB 的做法:
当您创建一个新的 Cocoa Touch Class 文件时,选择从 UITableViewCell 子类化并选择创建 XIB 文件选项。之后,根据需要配置 XIB 的 View ,并在 Identity Inspector 中设置重用标识符。
如果您想从屏幕截图中获得布局,请拖动 UIStackView
, 将其约束设置为顶部、底部、前导和尾随单元格的 contentView,将对齐设置为水平,然后选择 fill equally
并拖动 3 UIButton
s 在里面,stackView 将确保很好地安排它们
在您的 viewController 中不要忘记将单元格注册到 tableView,然后从 cellForRowAtIndexPath
返回该单元格
关于ios - 如何向 UITableViewCells Swift 添加多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59777938/
我是一名优秀的程序员,十分优秀!