Search code examples
swiftuipickerview

UIPickerView Margin Left


For a UIPickerView with a title, I'm looking for a way to provide a left margin to the title. Currently, the first two words seem to be cropped.

I'm using this UIPickerView method to assign title.

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let pickerLabel = UILabel()
    let title = NSAttributedString(string: castProductDetails[row].price, attributes:[.font: FontFamily.Roboto.medium.font(size: 16.0), .foregroundColor: Asset.Colors.primaryText.color] )
    pickerLabel.attributedText = title
    return pickerLabel
}

Adding screenshot for reference.


Solution

  • This worked for me.

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        
        let margin : CGFloat = 20.0
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.firstLineHeadIndent = margin
        paragraphStyle.headIndent = margin
        
        let title = NSMutableAttributedString(string: yourArrayHere[row])
        title.addAttribute(.paragraphStyle,
                           value: paragraphStyle,
                           range: NSRange(location: 0, length: title.length))
        
        let pickerLabel = UILabel()
        pickerLabel.attributedText = title
        return pickerLabel
    }