2018년 3월 9일 금요일

UIPickerView의 선택된 텍스트 색상 변경, 선택 라인의 색상 변경을 하려면?

어쩔수 없이 UI작업이 디자인 가이드를 우선으로 해야 하는 경우 기본적인 UIPickerView를 변경 해야 하는 경우가 있다.


UIPikckerView를 디폴트로 사용하면 데이터소스로 데이터 값정도를 변경 할 수 있다.

위와 같이 선택라인의 색상을 변경 시키거나 선택된 텍스트의 컬러를 변경 시키는 작업은 코드를 이용 해야 한다.

첫번째 선택된 Text의 컬러를 변경 하기 위해서는 AttributeString을 리턴 하는 아래의 메서드를 구현 해야 한다.

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString?
{

}

선택된 row 일때와 그렇지 않을때의 컬러를 결정 하여 NSAttributedString을 리턴 해야 한다.

1,2,3,4와 같은 UIPickerView 의 표출될 문자열 스트링 어레이가. pickerData 인 경우 
아래의 코드는 선택된 텍스트의 색상을 blue, 선택되지 않은 색상은 black으로 표출 하는 코드이다.
    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        var color: UIColor!
        if pickerView.selectedRow(inComponent: component) == row {
            color = UIColor.blue
        } else {
            color = UIColor.black
        }
        
        let attributes: [NSAttributedStringKey: Any] = [
            NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): color,
            NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue): UIFont.systemFont(ofSize: 15)
        ]
        
        return NSAttributedString(string: pickerData[row], attributes: attributes)
    }



다음은 선택 라인의 색상을 변경 해야 하는데 기본 UIPickerView는 Property로 제공하지 않는다.

UIPickerView를 서브클래싱 하여 CustomPickerView class를 생성 한다음 다음의 두 라인이 을 찾아서 색상을 변경 하는 코드를 추가 해야 한다.

didAddSubview 메서드를 오버라이딩 하여 서브뷰 중에 height가 1인 값의 즉 두선을 찾아 색상을 변경 한다.

 @IBDesignable와 @IBInspectable을 이용하여 스토리보드에서 변경 사항을 확인 까지 가능 하도록 다음과 같이 클래스를 생성 하면 된다.

//
//  CustomPickerView.swift
//  datetimepickerDemo
//
//  Created by  sparrow on 2018. 3. 8..
//  Copyright © 2018년  sparrow. All rights reserved.
//

import UIKit

@IBDesignable
class CustomPickerView: UIPickerView
{
    @IBInspectable var selectorColor: UIColor? = nil
    
    override func didAddSubview(_ subview: UIView) {
        super.didAddSubview(subview)
        if let color = selectorColor
        {
            if subview.bounds.height <= 1.0
            {
                subview.backgroundColor = color
            }
        }
    }
}


스토리 보드상에서 selectorColor을 설정 하면 바로 색상이 적용된다.








댓글 1개:

carb cycling meal plan pdf|Carb Cycling :

Every other method of editing color on every other platform lets you do so in real time.
But the top of the line Photoshop needs you to click OK to even see the color you selected.
PHOTOSHOP IS THE REASON I SWITCHED FROM DESIGNER TO DEVELOPER