UILabel 높이를 텍스트로 조정
텍스트에 맞게 높이를 조정하려는 레이블이 있습니다. 이것이 제가 지금 작성한 코드입니다.
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
편집하다:
문제는이 코드 부분이 아니므로 내 수정 사항은 문제 자체에 있습니다. 다른 사람들에게 여전히 유용 할 수 있습니다!
나는 이것을 놀이터에 두었고 그것은 나를 위해 작동합니다.
Swift 4.0 업데이트
import UIKit
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
let font = UIFont(name: "Helvetica", size: 20.0)
var height = heightForView("This is just a load of text", font: font, width: 100.0)
스위프트 3 :
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
AutoLayout을 사용하는 경우UILabel
구성 UI로만 높이를 조정할 수 있습니다 .
iOS8 이상
- 제약 조건 선행 / 후행 설정
UILabel
- 그리고 줄을
UILabel
1에서 0으로 변경하십시오.
iOS7의 경우
- 먼저 , 포함 높이를 추가해야합니다.
UILabel
- 그런 다음 Relation from
Equal
to toGreater than or Equal
- 마지막으로 행을
UILabel
1에서 0 으로 변경합니다.
당신의 UILabel
의지는 자동으로 텍스트에 따라 높이를 증가
원하는 경우이 확장 프로그램을 만듭니다.
extension UILabel {
func setSizeFont (sizeFont: CGFloat) {
self.font = UIFont(name: self.font.fontName, size: sizeFont)!
self.sizeToFit()
}
}
강력한 작업 솔루션이 있습니다.
layoutSubviews에서 :
_title.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 0)
_title.sizeToFit()
_title.frame.size = _title.bounds.size
텍스트 세터에서 :
_title.text = newValue
setNeedsLayout()
UPD. 물론이 UILabel 설정으로 :
_title.lineBreakMode = .ByWordWrapping
_title.numberOfLines = 0
설정하기 만하면 :
label.numberOfLines = 0
레이블은 입력 한 텍스트 양에 따라 높이를 자동으로 조정합니다.
Anorak의 답변에 따라 Zorayr의 우려에도 동의하므로 UILabel을 제거하고 CGFloat 만 반환하는 두 줄을 추가했습니다. 원래 코드가 UIabel을 추가하지 않았기 때문에 도움이되는지 모르겠지만 오류가 발생하지 않으므로 아래 코드를 사용하고 있습니다.
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
var currHeight:CGFloat!
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
currHeight = label.frame.height
label.removeFromSuperview()
return currHeight
}
@Anorak 답변에 따라이 확장을 String에 추가하고 매개 변수로 삽입을 보냈습니다. 많은 경우 텍스트에 패딩이 필요하기 때문입니다. 어쨌든, 아마도 당신은 이것이 유용하다는 것을 알게 될 것입니다.
extension String {
func heightForWithFont(font: UIFont, width: CGFloat, insets: UIEdgeInsets) -> CGFloat {
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width + insets.left + insets.right, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = self
label.sizeToFit()
return label.frame.height + insets.top + insets.bottom
}
}
In swift 4.1 and Xcode 9.4.1
Only 3 steps
Step 1)
//To calculate height for label based on text size and width
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
Step 2)
//Call this function
let height = heightForView(text: "This is your text", font: UIFont.systemFont(ofSize: 17), width: 300)
print(height)//Output : 41.0
Step 3)
//This is your label
let proNameLbl = UILabel(frame: CGRect(x: 0, y: 20, width: 300, height: height))
proNameLbl.text = "This is your text"
proNameLbl.font = UIFont.systemFont(ofSize: 17)
proNameLbl.numberOfLines = 0
proNameLbl.lineBreakMode = .byWordWrapping
infoView.addSubview(proNameLbl)
The solution suggested by Anorak as a computed property in an extension for UILabel:
extension UILabel
{
var optimalHeight : CGFloat
{
get
{
let label = UILabel(frame: CGRectMake(0, 0, self.frame.width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = self.lineBreakMode
label.font = self.font
label.text = self.text
label.sizeToFit()
return label.frame.height
}
}
}
Usage:
self.brandModelLabel.frame.size.height = self.brandModelLabel.optimalHeight
Here is how to calculate the text height in Swift. You can then get the height from the rect and set the constraint height of the label or textView, etc.
let font = UIFont(name: "HelveticaNeue", size: 25)!
let text = "This is some really long text just to test how it works for calculating heights in swift of string sizes. What if I add a couple lines of text?"
let textString = text as NSString
let textAttributes = [NSFontAttributeName: font]
let textRect = textString.boundingRectWithSize(CGSizeMake(320, 2000), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
just call this method where you need dynamic Height for label
func getHeightforController(view: AnyObject) -> CGFloat {
let tempView: UILabel = view as! UILabel
var context: NSStringDrawingContext = NSStringDrawingContext()
context.minimumScaleFactor = 0.8
var width: CGFloat = tempView.frame.size.width
width = ((UIScreen.mainScreen().bounds.width)/320)*width
let size: CGSize = tempView.text!.boundingRectWithSize(CGSizeMake(width, 2000), options:NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: tempView.font], context: context).size as CGSize
return size.height
}
Swift 4.0
self.messageLabel = UILabel(frame: CGRect(x: 70, y: 60, width:UIScreen.main.bounds.width - 80, height: 30)
messageLabel.text = message
messageLabel.lineBreakMode = .byWordWrapping //in versions below swift 3 (messageLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping)
messageLabel.numberOfLines = 0 //To write any number of lines within a label scope
messageLabel.textAlignment = .center
messageLabel.textColor = UIColor.white
messageLabel.font = messageLabel.font.withSize(12)
messageLabel.sizeToFit()
Blockquote NSParagraphStyle.LineBreakMode, apply to entire paragraphs, not words within paragraphs.This property is in effect both during normal drawing and in cases where the font size must be reduced to fit the label’s text in its bounding box. This property is set to byTruncatingTail by default.
This link describes the storyboard way of doing the same
Swift 4.0
텍스트 / 레이블 높이를 계산하는 대신 (동적) 텍스트를 삽입 한 후 레이블 크기를 조정합니다.
myLabel이 문제의 UILabel이라고 가정합니다.
let myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: *somewidth*, height: *placeholder, e.g. 20*))
myLabel.numberOfLines = 0
myLabel.lineBreakMode = .byWordWrapping
...
이제 재미있는 부분이 있습니다.
var myLabelText: String = "" {
didSet {
myLabel.text = myLabelText
myLabel.sizeToFit()
}
}
라벨 높이를 계산 하는 Swift 4.1 확장 방법 :
extension UILabel {
func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
}
신속하게 레이블을 동적으로 만들려면 높이를 constarint로 지정하지 말고 스토리 보드에서 줄의 레이블 번호를 0으로 지정하면 하단 제약 조건도 제공됩니다. 이것이 콘텐츠 크기에 따라 동적 레이블을 처리하는 가장 좋은 방법입니다.
참고 URL : https://stackoverflow.com/questions/25180443/adjust-uilabel-height-to-text
'program story' 카테고리의 다른 글
Xcode 4.4 오류-앱 실행 대기 시간이 초과되었습니다. (0) | 2020.08.17 |
---|---|
Maven : net.sf.json-lib 누락 (0) | 2020.08.17 |
O (1), O (n log n) 및 O (log n) 복잡도를 갖는 알고리즘의 예 (0) | 2020.08.17 |
파이썬에서 nosetest / unittest로 출력을 어설 션하는 방법은 무엇입니까? (0) | 2020.08.17 |
TabLayout을 사용할 때 탭 배경색을 어떻게 변경합니까? (0) | 2020.08.17 |