programing

UI 레이블에서 텍스트의 픽셀 너비

sourcetip 2023. 9. 9. 23:12
반응형

UI 레이블에서 텍스트의 픽셀 너비

UIL 라벨을 그려야 합니다.따라서 저는 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

UIL 레이블이 전체 레이블과 같은 길이의 줄로 쳐져 있지만 텍스트는 더 짧을 수 있습니다.선을 적절하게 그릴 수 있도록 텍스트의 길이를 픽셀 단위로 결정할 수 있는 방법이 있습니까?

저는 다른 해결책도 알고 있습니다. :)

최고, 에릭

NS 문자열에 크기가 있습니다.WithAttributes: 이에 사용할 수 있는 메서드입니다.CGSize 구조를 반환하므로 다음과 유사한 작업을 수행하여 레이블 내부의 텍스트 너비를 찾을 수 있습니다.

iOS 7 이상

CGSize textSize = [[label text] sizeWithAttributes:@{NSFontAttributeName:[label font]}];

CGFloat strikeWidth = textSize.width;

iOS <7

iOS7 이전에는 사이즈를 사용해야 했습니다.WithFont: 메서드.

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

CGFloat strikeWidth = textSize.width;

UILabel에는 위와 같이 레이블에 대한 글꼴 세부 정보를 동적으로 가져오는 데 사용할 수 있는 글꼴 속성이 있습니다.

여기 Swift에서 보다 나은 솔루션을 제공합니다.
업데이트:
위해서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

이거면 돼요.먹어봐.

NSDictionary *attrDict = @{NSFontAttributeName : [GenericUtility getOpenSansRegularFontSize:12]};
CGSize stringBoundingBox = [selectedReservationModel.DateLabel sizeWithAttributes: attrDict];
lblDeliveryDateWidth = stringBoundingBox.width;

언급URL : https://stackoverflow.com/questions/1340667/pixel-width-of-the-text-in-a-uilabel

반응형