2015-12-03 41 views
1

試圖將UIPickerView中兩個組件中的文本右對齊/左對齊。它在所選區域內正確顯示,但文本在其他地方重疊。iOS Swift:UIPickerView文本對齊

任何想法我在這裏做錯了嗎?

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { 
    let pickerLabel = UILabel() 
    var titleData: String! 

    if component == 0 { 
     if pickerView.tag == 0 { 
      titleData = weightData[row].description 
     } else { 
      titleData = bodyFatData[row].description 
     } 
     pickerLabel.textAlignment = .Right 

    } else { 
     titleData = decimalData[row].description 
     pickerLabel.textAlignment = .Left 
    } 

    let myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(22.0),NSForegroundColorAttributeName: 

    UIColor.blackColor()]) 
     pickerLabel.attributedText = myTitle 

     return pickerLabel 
    } 

enter image description here

編輯:

當我加入這行

pickerLabel.frame.size = CGSizeMake(165, 26)

它確實有效果,但所選擇的/未選中的行仍然對齊。

enter image description here

+0

它會幫助給你的UILabel一個大小? – matt

+2

另外,不要將標籤文本對齊與屬性文本組合在一起。如果要使用屬性文本,請在屬性文本段落樣式中包含對齊。 – matt

+0

嘗試添加大小到'pickerLabel'並且實現'rowHeightForComponent'函數。 –

回答

0

我認爲你只是簡單俯瞰這一功能的可能性:

// Swift 
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { 
    return CGFloat(50.0) 
} 

centered and tight components

默認情況下,組件將中心對齊,並且它出現在整個拾取還將中心對齊。如果省略textAlignment,則組件(列)中的所有值將排隊。