Swift UIPickerView 设置上下横线颜色教程
要设置 UIPickerView 上下两根横线的颜色,可以通过 UIPickerViewDelegate 的方法来实现。具体步骤如下:\n\n1. 首先,在你的 ViewController 中,确认你的 ViewController 遵循 UIPickerViewDelegate 协议。可以在 ViewController 的类定义中添加 UIPickerViewDelegate,如下所示:\n\nswift\nclass ViewController: UIViewController, UIPickerViewDelegate {\n\n\n2. 然后,在你的 ViewController 中,实现 UIPickerViewDelegate 的 viewForRow 方法。该方法返回一个 UIView 对象,可以用来自定义 UIPickerView 中每一行的视图。在这个方法中,你可以设置每一行的背景色,并添加上下两根横线。具体代码如下:\n\nswift\nfunc pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {\n // 创建一个 UILabel 作为每一行的视图\n let label = UILabel()\n \n // 设置 label 的文本、字体、颜色等属性\n label.text = "Row (row)"\n label.font = UIFont.systemFont(ofSize: 18)\n label.textColor = .black\n \n // 设置 label 的背景色\n label.backgroundColor = .white\n \n // 添加上下两根横线\n let topLine = UIView(frame: CGRect(x: 0, y: 0, width: pickerView.frame.width, height: 1))\n topLine.backgroundColor = .red\n label.addSubview(topLine)\n \n let bottomLine = UIView(frame: CGRect(x: 0, y: pickerView.rowSize(forComponent: component).height - 1, width: pickerView.frame.width, height: 1))\n bottomLine.backgroundColor = .red\n label.addSubview(bottomLine)\n \n return label\n}\n\n\n在上面的代码中,我创建了一个 UILabel 对象作为每一行的视图,并设置了文本、字体和颜色等属性。然后,我设置了 label 的背景色,并添加了上下两根横线,分别为红色。\n\n3. 最后,在你的 ViewController 的 viewDidLoad 方法中,将 UIPickerView 的 delegate 设置为你的 ViewController。具体代码如下:\n\nswift\noverride func viewDidLoad() {\n super.viewDidLoad()\n \n // 设置 UIPickerView 的 delegate\n pickerView.delegate = self\n}\n\n\n在上面的代码中,我假设你的 UIPickerView 的实例名为 pickerView。\n\n这样,当你运行你的应用程序时,UIPickerView 中的每一行都会有上下两根红色的横线。你可以根据需要调整横线的颜色和样式。
原文地址: https://www.cveoy.top/t/topic/p0RM 著作权归作者所有。请勿转载和采集!