본문 바로가기

iPhone

UILabel에 중앙선(취소선) 표시하기. (UIStrikeLabel)

UILabel 에 Text 를 입력하고, 중앙선(취소선)을 표시하고 싶지 않으세요? ^^;


UILabel 레퍼런스를 샅샅이 뒤져봤지만,  Strike를 표시하는 속성이나 메소드가 없더라고요.
게다가, IB에서 폰트 설정에 Strike 를 설정하는 부분이 있지만, 적용이 되지 않고요..

결국, 고민 끝에 UILabel 을 상속받은 새로운 클래스를 정의해서 구현하기로 했습니다.
뭐.. 그냥, Frame 사이즈에서 중앙선 위치를 구한 뒤에 라인을 하나 그어주면 되겠다 싶었죠.

헌데! 한 가지 생각지 못한 결과가 나오더라고요. 
바로.. Frame 사이즈대로 중앙선의 With를 결정하니, UILabel 의 전체 사이즈. 즉, 입력 된 Text 부분을 제외한 나머지 여백에도 중앙선이 생기는 겁니다. 

그래서, Font 사이즈가 고려 된 Text의 총 With를 알아내야만 되겠더라고요~

UILabel 에 set 된 Text의 Size 알기.

CGSize textSize = [[UILabel text] sizeWithFont:[UILabel font]];

이렇게 하면, UILabel 내 set 된 Text의 Size를 알 수 있습니다. 

그럼, Size를 구하고 중앙선(취소선)은 언제 그려줘야 할까요?
UILabel 의 레퍼런스를 보면,  다음과 같은 메소드가 있더라고요. 

drawTextInRect:

Draws the receiver’s text (or its shadow) in the specified rectangle.

해서, 저는 메서드를 오버라이드 했습니다.

#define strikeHeight 1.0


@implementation UIStrikeLabel


- (void)drawTextInRect:(CGRect)rect {

[super drawTextInRect:rect];

CGContextRef context = UIGraphicsGetCurrentContext();

CGSize textSize = [[self text] sizeWithFont:[self font]];

CGFloat strikeWidth = textSize.width;

CGContextFillRect(context, CGRectMake(0, rect.size.height/2, strikeWidth, strikeHeight));

}



@end


여기에 BOOL값으로 Strike 를 사용자가 선택 할 수 있게 하고,

if([self strike]) {

CGSize textSize = [[self text] sizeWithFont:[self font]];

CGFloat strikeWidth = textSize.width;

CGContextFillRect(context, [self getStrikeRect:strikeWidth]);

}


중앙선(취소선)의 위치를 텍스트 정렬에 따라 맞춰준다면 쓸만한 컨트롤이 될 수 있겠네요 :)

switch ([self textAlignment]) {

default:

case UITextAlignmentLeft:

x = 0;

break;

case UITextAlignmentCenter:

x = (self.frame.size.width - strikeWidth) / 2.0;

break;

case UITextAlignmentRight:

x = self.frame.size.width - strikeWidth;

break;

}


간단하게 샘플을 추가 해 봤습니다. x 축 정렬만 적용 된 버전입니다. :)