I Have a pickerview which does not display text properly as off iOS 14. Does anyone know how to fix this? It seems like there is a subview covering the text?
Is it because I'm using a custom label?
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
}
Just add margin-left to the label would do the trick.
After the fix
Raw code:
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
}
}
}
You can set the attributedString, as Nguyen suggested, in the ViewForRow method and edit your code like this
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])
let margin : CGFloat = 12.0
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = margin
paragraphStyle.headIndent = margin
myTitle.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: myTitle.length))
pickerLabel.attributedText = myTitle
return pickerLabel
}
I'm using an even simpler label-generation method; for now my workaround is to use center alignment, as in the following example.
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
}
I wondered if this was a font-dependent defect, but since you're using the system font I conclude that it probably isn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With