Swift - 让UIPickerView里的选项文字自动换行(多行显示)
作者:hangge | 2018-05-30 08:10
1,问题描述
我们知道默认情况下,选择框(UIPickerView)里每个选项只能显示一行文字。当内容过多的时候就会显示不全(以省略号结尾)。

如果我们需要让用户能看全每个选项的文字内容,最好的办法就是让内容能多行显示。
2,实现方法
(1)通过 pickerView的 viewForRow 这个代理方法,我们可以使用自定义的 view 作为选项视图。
(2)这里我们直接使用 UILabel 作为选项视图,同时将 label 的 numberOfLines 属性设置为需要显示的行数即可。(这里要注意的是 pickerView 的行高,确保行高能容纳下需要显示的行数。否则 numberOfLines 设置的再大也没用。)
(3)当然也可以将 numberOfLines 设置为 0,表示限制行数,这样文字需要显示几行就显示几行。(当然仍然不能超过行高)
3,演示样例
(1)效果图

(2)样例代码
import UIKit
class ViewController:UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{
var pickerView:UIPickerView!
//选择框数据
var mulan = ["唧唧复唧唧,木兰当户织, 不闻机杼声,唯闻女叹息。",
"问女何所思,问女何所忆, 女亦无所思,女亦无所忆。",
"昨夜见军帖,可汗大点兵, 军书十二卷,卷卷有爷名。",
"阿爷无大儿,木兰无长兄,愿为市鞍马,从此替爷征。",
"东市买骏马,西市买鞍鞯,南市买辔头,北市买长鞭。",
"旦辞爷娘去,暮宿黄河边,不闻爷娘唤女声,但闻黄河流水鸣溅溅。",
"旦辞黄河去,暮至黑山头,不闻爷娘唤女声,但闻燕山胡骑鸣啾啾。",
]
override func viewDidLoad() {
super.viewDidLoad()
//关闭导航栏半透明效果
self.navigationController?.navigationBar.isTranslucent = false
pickerView = UIPickerView()
//将dataSource设置成自己
pickerView.dataSource = self
//将delegate设置成自己
pickerView.delegate = self
//设置选择框的默认值
pickerView.selectRow(1,inComponent:0,animated:true)
pickerView.selectRow(2,inComponent:1,animated:true)
self.view.addSubview(pickerView)
}
//设置选择框的列数为3列,继承于UIPickerViewDataSource协议
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
//设置选择框的行数为9行,继承于UIPickerViewDataSource协议
func pickerView(_ pickerView: UIPickerView,
numberOfRowsInComponent component: Int) -> Int {
return mulan.count
}
//设置列宽
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int)
-> CGFloat {
if(0 == component){
return 100
}else{
return pickerView.frame.width - 120
}
}
//设置行高
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int)
-> CGFloat {
return 50
}
//自定义选项视图
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int,
forComponent component: Int, reusing view: UIView?) -> UIView {
var pickerLabel = view as? UILabel
if pickerLabel == nil {
pickerLabel = UILabel()
pickerLabel?.font = UIFont.systemFont(ofSize: 16)
}
pickerLabel?.numberOfLines = 0 //不限制行数
if component == 0 {
pickerLabel?.text = "数据\(row)"
pickerLabel?.textAlignment = .center
} else {
pickerLabel?.text = mulan[row]
pickerLabel?.textAlignment = .left
}
return pickerLabel!
}
}
全部评论(0)