From 7b9f49233e7d514c5909a3563a0aa69f228bb947 Mon Sep 17 00:00:00 2001 From: EunsuSeo01 Date: Mon, 30 Dec 2024 04:54:32 +0900 Subject: [PATCH] =?UTF-8?q?[Feat]=20#319=20-=20text=EC=97=90=20=EB=94=B0?= =?UTF-8?q?=EB=9D=BC=20UILabel=20=EC=A4=84=EB=B0=94=EA=BF=88=EC=9D=B4=20?= =?UTF-8?q?=EB=AA=87=20=EB=B2=88=20=EB=90=A0=EC=A7=80=20=EC=95=8C=EB=A0=A4?= =?UTF-8?q?=EC=A3=BC=EB=8A=94=20=ED=95=A8=EC=88=98=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit UILabel+에 추가함 --- .../Global/Extensions/UILabel+.swift | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Hankkijogbo/Hankkijogbo/Global/Extensions/UILabel+.swift b/Hankkijogbo/Hankkijogbo/Global/Extensions/UILabel+.swift index a9eb10ae..8461efa5 100644 --- a/Hankkijogbo/Hankkijogbo/Global/Extensions/UILabel+.swift +++ b/Hankkijogbo/Hankkijogbo/Global/Extensions/UILabel+.swift @@ -101,4 +101,26 @@ extension UILabel { formatter.numberStyle = .decimal self.text = (formatter.string(from: NSNumber(value: price)) ?? "\(price)") + StringLiterals.Common.won } + + /// 텍스트 양에 따른 Label의 줄바꿈이 몇 번 될지 알려주는 함수 + /// - maxWidth : label이 차지하게 되는 최대 width + func calculateNumberOfLines(maxWidth: CGFloat) -> Int { + guard let text = text, let font = font else { return 0 } + + // UILabel의 텍스트와 폰트로 텍스트가 차지하는 전체 높이 계산 + let textAttributes: [NSAttributedString.Key: Any] = [.font: font] + let size = CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude) + let boundingBox = NSString(string: text).boundingRect( + with: size, + options: .usesLineFragmentOrigin, + attributes: textAttributes, + context: nil + ) + + // 한 줄이 차지하는 높이 + let singleLineHeight = font.lineHeight + + // 전체 텍스트 높이를 한 줄 높이로 나눈 값을 줄 수로 리턴 + return Int(ceil(boundingBox.height / singleLineHeight)) + } }