당신은 그들을 문자열 높이와 폭을 계산하고 설정하려면 다음을 사용할 수 있습니다
import Foundation
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let width = "Hello World".stringWidth // 74.6
let height = "Hello World".stringHeight // 16.7
let headerLabel = UILabel()
headerLabel.frame = CGRect(x: 0, y: 0, width: width, height: height)
headerLabel.center = CGPoint(x: screenSize.width/2, y: 245)
}
}
extension String {
var stringWidth: CGFloat {
let constraintRect = CGSize(width: UIScreen.main.bounds.width, height: .greatestFiniteMagnitude)
let boundingBox = self.trimmingCharacters(in: .whitespacesAndNewlines).boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)], context: nil)
return boundingBox.width
}
var stringHeight: CGFloat {
let constraintRect = CGSize(width: UIScreen.main.bounds.width, height: .greatestFiniteMagnitude)
let boundingBox = self.trimmingCharacters(in: .whitespacesAndNewlines).boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)], context: nil)
return boundingBox.height
}
}
줄 수를 0으로 설정합니다. – Shades
프로그래밍 방식으로 완료되었으므로 프레임을 설정할 수 있습니까? – SwiftyJD