我有一个UIPickerView如何让它成为多线?我有一些很长的文字。
这是我的代码。
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
var returnResult: String = ""
if pickerView.tag == 1 {
//This picker has long text
let position: UInt = UInt(row)
returnResult = list.objectAtIndex(position).Description.Value;
} else if pickerView.tag == 2 {
returnResult = questionTwoOptions[row]
} else if pickerView.tag == 3 {
returnResult = questionThreeOptions[row]
} else {
returnResult = ""
}
print(returnResult)
return returnResult
}
这是我的viewForRow方法
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
let label = UILabel(frame: CGRectMake(0, 0, 400, 44));
label.lineBreakMode = .ByWordWrapping;
label.numberOfLines = 0;
//view!.addSubview(label)
return label;
}
答案 0 :(得分:17)
您可以尝试使用自定义视图
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
let label = UILabel(frame: CGRectMake(0, 0, 400, 44));
label.lineBreakMode = .ByWordWrapping;
label.numberOfLines = 0;
label.text = arr[row]
label.sizeToFit()
return label;
}
如果您的内容可能超过两行,您还可以设置行高
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 80
}
答案 1 :(得分:3)
UILabel
是UIView
的子类。UIPickerView
创建视图,其他为视图提供文本的委托方法现在无关紧要。height:
期间更改UILabel
参数,如果需要更多空间,请调整return 80.0
行高。首先添加委托方法以指示行高。调整为最适合您显示目的的值。
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 80.0
}
接下来添加委托方法以提供视图。
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label: UILabel
if let view = view {
label = view as! UILabel
}
else {
label = UILabel(frame: CGRect(x: 0, y: 0, width: pickerView.frame.width, height: 400))
}
label.text = myTitleStrings[row]
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.sizeToFit()
return label
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label: UILabel
if let view = view {
label = view as! UILabel
}
else {
label = UILabel(frame: CGRect(x: 0, y: 0, width: pickerView.frame.width, height: 400))
}
let title = myTitleStrings[row]
let attributes = [NSAttributedStringKey.foregroundColor: UIColor.white,
NSAttributedStringKey.font: UIFont(name: "HelveticaNeue", size: 18.0)!]
label.attributedText = NSAttributedString(string: title, attributes: attributes)
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.sizeToFit()
return label
}
答案 2 :(得分:2)
您将不得不更改rowHeightForComponent(UIPickerView)
类似的东西:
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat
{
return 70.0
}
你可以在多行中看到它,其他所有你都做得很好。