
Использование простой версии со строкой = «4 / 23»
Это код метки:
Код: Выделить всё
private let numberLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 18, weight: .bold)
label.textColor = .black
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(numberLabel)
backgroundColor = UIColor.systemGray5
layer.borderColor = UIColor.black.cgColor
layer.borderWidth = 1.0
NSLayoutConstraint.activate([
numberLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
numberLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
])
// Set the numberLabel to fill the entire cell
NSLayoutConstraint.activate([
numberLabel.topAnchor.constraint(equalTo: contentView.topAnchor),
numberLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
numberLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
numberLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
])
}
Я установил метку следующим образом:
numberLabel.attributedText = createFormattedString(for: Number)
numberLabel.backgroundColor = .red
Вот функция:
Код: Выделить всё
func createFormattedString(for string: String) -\> NSAttributedString {
// If the string contains a '/', handle the special case
if let slashRange = string.range(of: "/") {
let topPart = string\[slashRange.upperBound...\] // Everything after '/'
let bottomPart = string\[..\
Подробнее здесь: [url]https://stackoverflow.com/questions/79336243/position-nsattributedstring[/url]
Мобильная версия