Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing font and its size of a picker in swift

With Objective-C, I used the code shown below to set/change font family and size of a picker:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UILabel* tView = (UILabel*)view;
if (!tView){
    tView = [[UILabel alloc] init];
    // Setup label properties - frame, font, colors etc
    tView.font = [UIFont fontWithName:@"Times New Roman" size:fontsize];;
}
tView.text = [_mysitedata findKeyForRow:row];
NSLog(@"C key:%@ row:%ld comp:%ld", tView.text, (long int)row, (long int)component);
return tView;
}

However, Swift does not accept a cast from UIView to UILabel and hence I can not follow this path which would look something like shown below:

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
    let label = view as! UILabel
    label.font = UIFont(name: "Times New Roman", size: 1.0)
    label.text = pickerData[row]
    return label
}

The first stament (let label ....) throuws an exception at run time:

EXC-BAD INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

like image 926
Robert Brusa Avatar asked Nov 11 '15 16:11

Robert Brusa


2 Answers

For Swift 3

 func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let label = (view as? UILabel) ?? UILabel()

    label.textColor = .black
    label.textAlignment = .center
    label.font = UIFont(name: "SanFranciscoText-Light", size: 18)

    // where data is an Array of String
    label.text = pickerData[row]

    return label
  }
like image 157
Wilson Avatar answered Sep 21 '22 16:09

Wilson


For swift 2.3

 func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView{

        var label = view as! UILabel!
        if label == nil {
            label = UILabel()
        }

        label.font = UIFont(name: "Lato-Regular", size: 17)!
        label.text =  dataArray[row] as? String
        label.textAlignment = .Center
        return label

    }

For Swift 3

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView{

        print("Returning Custom label")
        var label = view as! UILabel!
        if label == nil {
            label = UILabel()
        }

        label?.font = UIFont(name: "Lato-Regular", size: 14)!
        label?.text =  dataArray[row] as? String
        label?.textAlignment = .center
        return label!

    }
like image 26
Nischal Hada Avatar answered Sep 20 '22 16:09

Nischal Hada