반응형
UILabel 텍스트의 픽셀 너비
취소 선이있는 UILabel을 그려야합니다. 따라서 UILabel을 서브 클래 싱하고 다음과 같이 구현했습니다.
@implementation UIStrikedLabel
- (void)drawTextInRect:(CGRect)rect{
[super drawTextInRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextFillRect(context,CGRectMake(0,rect.size.height/2,rect.size.width,1));
}
@end
UILabel은 전체 레이블만큼 길지만 텍스트는 더 짧을 수 있습니다. 선을 적절하게 그릴 수 있도록 텍스트 길이를 픽셀 단위로 결정하는 방법이 있습니까?
알려진 경우 다른 솔루션에도 열려 있습니다. :)
최고, Erik
NSString에는 이를 위해 사용할 수 있는 sizeWithAttributes : 메소드가 있습니다. CGSize 구조를 반환하므로 다음과 유사한 작업을 수행하여 레이블 내부의 텍스트 너비를 찾을 수 있습니다.
iOS 7 이상
CGSize textSize = [[label text] sizeWithAttributes:@{NSFontAttributeName:[label font]}];
CGFloat strikeWidth = textSize.width;
iOS <7
iOS7 이전에는 sizeWithFont : 메소드 를 사용해야했습니다 .
CGSize textSize = [[label text] sizeWithFont:[label font]];
CGFloat strikeWidth = textSize.width;
UILabel에는 위에서 수행 한 것처럼 레이블의 글꼴 세부 정보를 동적으로 가져 오는 데 사용할 수있는 글꼴 속성이 있습니다.
도움이 되었기를 바랍니다 :)
더 나은 솔루션, 여기 Swift :
Update :
For Swift 3/4
:
@IBOutlet weak var testLabel: UILabel!
// in any function
testLabel.text = "New Label Text"
let width = testLabel.intrinsicContentSize.width
let height = testLabel.intrinsicContentSize.height
print("width:\(width), height: \(height)")
이전 답변 :
yourLabel?.text = "Test label text" // sample label text
let labelTextWidth = yourLabel?.intrinsicContentSize().width
let labelTextHeight = yourLabel?.intrinsicContentSize().height
이 샘플이 도움이되기를 바랍니다 (iOS> 7).
NSString *text = @" // Do any additional setup after loading the view, typically from a nib.";
CGRect rect = CGRectZero;
NSDictionary *attrDict = @{NSFontAttributeName : [UIFont systemFontOfSize:17]};
rect = [text boundingRectWithSize:CGSizeMake(100,9999)
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:attrDict
context:Nil];
UILabel *lbl = [[UILabel alloc] init];
lbl.text = text;
rect.origin = CGPointMake(50, 200);
lbl.frame = rect;
lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.numberOfLines = 0;
[self.view addSubview:lbl];
참고 URL : https://stackoverflow.com/questions/1340667/pixel-width-of-the-text-in-a-uilabel
반응형
'program story' 카테고리의 다른 글
Android 앱 리소스에서 JSON 파일 사용 (0) | 2020.10.13 |
---|---|
android : 바이트를 dex로 변환하는 중 오류 발생 (0) | 2020.10.13 |
Xcode 8에서 줄 삭제 키보드 단축키를 어떻게 만듭니 까? (0) | 2020.10.13 |
LINQ를 사용하여 항목을 목록 맨 위로 이동 (0) | 2020.10.13 |
부트 스트랩 navbar 활성 상태가 작동하지 않음 (0) | 2020.10.13 |