我试图调整标签大小以适应文字数量,但发布的答案here需要更多解释。
对我来说,我有三个标签:货币,整数金额,双金额:
我有三个标签,因为货币和双金额的风格都不同于整数金额。如果我以错误的方式行事,请纠正我,因为我不能只为这三个人制作一个标签。
这三个人都有top-right
最终我必须删除静态值,但是当我应用下面的代码时,注意到有效:
viewDidLoad()或viewDidAppear():
integerAmountLabel.sizeToFit()
integerAmountLabel.text = "1"
// or integerAmountLabel = "280,000"
期望:£1.00
或£280,000.00
。我得到了什么:£1 .00
或£ 1.00
答案 0 :(得分:2)
正如Aman Gupta所说,使用属性字符串。这是一个解释如何操作的游乐场代码:
import UIKit
import PlaygroundSupport
var str = "Hello, playground"
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 300))
PlaygroundPage.current.liveView = view
// set up view hierarchy
view.backgroundColor = .blue
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[label]-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["label": label]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[label]-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["label": label]))
// set up atributes
let currencyAttributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20), NSForegroundColorAttributeName: UIColor.white]
let integerAmountAttributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 30), NSForegroundColorAttributeName: UIColor.white]
let decimalAmountAttributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16), NSForegroundColorAttributeName: UIColor(white: 1, alpha: 0.7)]
// set up formatter
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.currency
formatter.locale = Locale(identifier: "en_GB")
let amount = 8001.9
let text = formatter.string(from: NSNumber(value: amount))!
let nsText = text as NSString
// calculate ranges
let currencyRange = NSRange(location: 0, length: 1)
let decimalPointRange = nsText.range(of: ".")
var integerAmountLocation = currencyRange.location + currencyRange.length
var integerAmountLength = decimalPointRange.location - integerAmountLocation
var integerAmountRange = NSRange(location: integerAmountLocation, length: integerAmountLength)
// configure attributed string
var attributedText = NSMutableAttributedString(string: text, attributes: decimalAmountAttributes)
attributedText.setAttributes(currencyAttributes, range: currencyRange)
attributedText.setAttributes(integerAmountAttributes, range: integerAmountRange)
label.attributedText = attributedText
你可以在这里找到整个游乐场:source
答案 1 :(得分:1)