ios - 如何向 UITableViewCells Swift 添加多个按钮
问题描述
我正在使用 Xcode 和 Swift 5 创建一个简单的 iOS 应用程序,用户可以在其中选择一个主题,然后背景会改变颜色。我想通过在表格视图的单元格上添加按钮来实现这一点。我知道如何将一个按钮添加到表格视图,但我不知道如何将多个按钮放入表格视图单元格。
这是一个表格视图单元格,其中添加了一个按钮:
ps:忽略按钮内的文字
我想要的是每边一个按钮,中间一个按钮,如下所示:
这是我的表视图控制器:
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 的视图,并在 Identity Inspector 中设置重用标识符。
如果您想从屏幕截图中获得布局,请拖动 a UIStackView
,将其约束设置为顶部、底部、前导和尾随到单元格的 contentView,将对齐设置为水平,然后选择fill equally
并在其中拖动 3UIButton
秒,stackView一定会好好安排他们
在您的 viewController 中不要忘记使用 tableView 注册单元格,然后返回该单元格cellForRowAtIndexPath
推荐阅读
- php - how to split one array in to multiple arrays based on clientID in php
- json - ReactJS doesn't recognize a value in an object in an array
- php - Laravel 8 - Change existing migration
- nuxt.js - Nuxtjs add apple pay button
- kotlin - Kotlin - staticProperties and staticFunctions Does Not Include @JvmStatic Annotated Members
- javascript - 将变量从页面传递到页面反应
- macos - 戈朗。main.go 中只有 fmt.Println,但是进程被阻塞了
- azure-devops - Azure Devops 从模板返回变量
- java - React Native firebase 连接无法正常工作
- angular - 角度 MatInput css