为了在UITableViewCell上获得圆角并允许用户选择单元格背景颜色,您可以采用以下方法:
class CustomTableViewCell: UITableViewCell {
let customLabel: UILabel = {
let label = UILabel()
label.layer.cornerRadius = 10 // 设置圆角半径
label.layer.masksToBounds = true // 启用圆角
label.textAlignment = .center
label.numberOfLines = 1
return label
}()
}
class CustomTableViewCell: UITableViewCell {
let customLabel: UILabel = {
let label = UILabel()
label.layer.cornerRadius = 10 // 设置圆角半径
label.layer.masksToBounds = true // 启用圆角
label.textAlignment = .center
label.numberOfLines = 1
return label
}()
let colorButton: UIButton = {
let button = UIButton()
button.layer.cornerRadius = 10 // 设置圆角半径
button.layer.masksToBounds = true // 启用圆角
button.addTarget(self, action: #selector(colorButtonTapped), for: .touchUpInside)
return button
}()
@objc func colorButtonTapped() {
// 在这里实现颜色选择器的弹出
}
}
class CustomTableViewCell: UITableViewCell {
let customLabel: UILabel = {
let label = UILabel()
label.layer.cornerRadius = 10 // 设置圆角半径
label.layer.masksToBounds = true // 启用圆角
label.textAlignment = .center
label.numberOfLines = 1
return label
}()
let colorButton: UIButton = {
let button = UIButton()
button.layer.cornerRadius = 10 // 设置圆角半径
button.layer.masksToBounds = true // 启用圆角
button.addTarget(self, action: #selector(colorButtonTapped), for: .touchUpInside)
return button
}()
@objc func colorButtonTapped() {
// 在这里实现颜色选择器的弹出
let colorPicker = UIColorPickerViewController()
colorPicker.selectedColor = customLabel.backgroundColor
colorPicker.delegate = self
present(colorPicker, animated: true, completion: nil)
}
func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
customLabel.backgroundColor = viewController.selectedColor
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
cell.customLabel.text = "Custom Cell"
cell.colorButton.backgroundColor = cell.customLabel.backgroundColor
return cell
}
这样,您就可以在UITableViewCell上获得圆角,并允许用户选择单元格背景颜色了。
领取专属 10元无门槛券
手把手带您无忧上云