레이블이 TextField inset인 게시물을 표시합니다. 모든 게시물 표시
레이블이 TextField inset인 게시물을 표시합니다. 모든 게시물 표시

2016년 1월 9일 토요일

UITextField의 inset 적용하기

TextField의 입력 글자의 시작 위치를 어느 정도 들여 쓰기를 하는 방법이 IB로 처리 할 수 없다.
하지만 이러한 디자인요구사항은 있다.


import UIKit
@IBDesignable
class FormTextField: UITextField {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    @IBInspectable var inset: CGFloat = 0
    
    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, inset, inset)
    }
    
    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return textRectForBounds(bounds)
    }

}
inset을 처리 하는 코드를 별도의 UITextField 를 상속 받아 클래스를 선언 한다.

@IBDesignable와 @IBInspectable var 로 선언을 한
inset은 오른쪽 Utitlity 창에 표시 된다.



이렇게 만든 TextField 컨트롤은 글씨 들여 쓰기가 가능 하다.

아래의 그림의 Placeholder 텍스트의 표시를 보면 12픽셀 들여 쓰기가 되어 있다.





swift4
import UIKit
@IBDesignable
class FormTextField: UITextField {

    @IBInspectable var inset: CGFloat = 0
    
    //let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    
    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset))
    }
    
    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset))
    }
    
    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset))
    }
    

}