问题描述
我有一个pickerview,无法在iOS 14之外正常显示文本。有人知道如何解决此问题?似乎有一个覆盖文本的子视图?
func pickerView(_ pickerView: UIPickerView,viewForRow row: Int,forComponent component: Int,reusing view: UIView?) -> UIView {
let pickerLabel = UILabel()
let titleData = pickerDataSource[row]
pickerView.subviews[1].backgroundColor = .clear
pickerView.subviews[0].backgroundColor = .clear
let myTitle = NSAttributedString(string: titleData,attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 18),NSAttributedString.Key.foregroundColor:UIColor.black])
pickerLabel.attributedText = myTitle
return pickerLabel
}
解决方法
只需在标签上添加左边距即可。
原始代码:
extension UILabel {
func setMargins(margin: CGFloat = 10,_ leftMarginOnly: Bool = true) {
if let textString = self.text {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = margin
paragraphStyle.headIndent = margin
if !leftMarginOnly {
paragraphStyle.tailIndent = -margin
}
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(.paragraphStyle,value: paragraphStyle,range: NSRange(location: 0,length: attributedString.length))
attributedText = attributedString
}
}
}
,
我正在使用一种更简单的标签生成方法;现在,我的解决方法是使用中心对齐,如以下示例所示。
func pickerView(_ pickerView: UIPickerView,viewForRow row: Int,forComponent component: Int,reusing view: UIView?) -> UIView
{
let pickerLabel = UILabel()
pickerLabel.text = "Test string"
pickerLabel.font = UIFont(name: "Ropa Sans",size: 18)
pickerLabel.textColor = UIColor.white
pickerLabel.textAlignment = NSTextAlignment.center
}
我想知道这是否是字体相关的缺陷,但是由于您使用的是系统字体,因此得出的结论可能不是。
,您可以按照Nguyen的建议在ViewForRow方法中设置attributedString,然后像这样编辑代码
func pickerView(_ pickerView: UIPickerView,reusing view: UIView?) -> UIView {
let pickerLabel = UILabel()
let titleData = pickerDataSource[row]
pickerView.subviews[1].backgroundColor = .clear
pickerView.subviews[0].backgroundColor = .clear
let myTitle = NSAttributedString(string: titleData,attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 18),NSAttributedString.Key.foregroundColor:UIColor.black])
let margin : CGFloat = 12.0
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = margin
paragraphStyle.headIndent = margin
myTitle.addAttribute(.paragraphStyle,length: myTitle.length))
pickerLabel.attributedText = myTitle
return pickerLabel
}
,
一种破解方法是将下面的代码添加到 pickerView(viewForRow:)
pickerView.subviews[0].subviews.first?.subviews.last?.clipsToBounds = false
pickerView.subviews[0].subviews.first?.subviews
包含 3 个视图,最后一个是真正包裹您的视图的视图,其宽度小于选择器视图,因此会修剪实际内容。