Search code examples
swiftios8uipickerview

NSAttributedString in Swift


I'm having an UIPickerView in my ViewController. At first I wanted to use attributedTitleForRow()but I needed to make the font size smaller so I used viewForRow...reusingView(). As I didn't want to rewrite my code of attributedTitleForRow() I did the following:

let attributedString = pickerView(
    pickerView, attributedTitleForRow: row, 
        forComponent: component)

afterward I wanted to set the newView's property (an UILabel) .attributedText = attributedString I got an error from the line above: pickerView(...) -> $T4 is not identical to the rest wasn't displayed on my screen but usually the rest is only UInt8. I don't know where's the mistake. Any help would be great :]

The whole code in the viewForRow() function:

        var newView = view as? UILabel
        if newView == nil {
            newView = UILabel()
        }
        newView!.font = UIFont.systemFontOfSize(16.0)
        newView!.textColor = UIColor.blueColor()
        newView!.adjustsFontSizeToFitWidth = true
        newView!.minimumScaleFactor = 0.6
        newView!.attributedText = (
            pickerView(pickerView, attributedTitleForRow: row, 
                forComponent: component))!
        newView!.textAlignment = .Center
        return newView!

The line calling the other pickerView function doesn't work - not only the way it is now in the code above


Solution

  • Rewrite the key line with self and all will be well:

    newView!.attributedText = self.pickerView(
        pickerView, attributedTitleForRow:row, 
            forComponent:component)
    

    This will allow your code to compile.

    The reason is apparently that the pickerView in the method parameters is overshadowing your existing pickerView... method. Using self disambiguates.

    (However, I'm concerned that this is never going to work because this code will never be called. If attributedTitleForRow is implemented, perhaps viewForRow is ignored? You will have to experiment and see whether my concern is justified.)