这是我的自定义视图类: - 带标签的UIView - 我想添加一个标签作为带有约束的子视图
似乎在IB上显示
但不在模拟器中:
这是我的自定义视图:
我用:
setNeedsDisplay()
setNeedsLayout()
虽然没有帮助。
class StatusView: UIView {
private var titleLabel: UILabel?
convenience init() {
self.init(frame: .zero)
}
private func setupViews() {
let titleAttributed = NSMutableAttributedString(string: text)
let styleTitle = NSMutableParagraphStyle()
styleTitle.alignment = .center
titleAttributed.addAttribute(.paragraphStyle, value: styleTitle,
range: NSRange(location: 0, length: titleAttributed.length))
titleLabel?.attributedText = titleAttributed
let styleDesc = NSMutableParagraphStyle()
styleDesc.alignment = .center
self.addSubview(titleLabel!)
}
func commonSetup() {
self.backgroundColor = UIColor.green
self.titleLabel = UILabel(frame: .zero)
self.titleLabel!.translatesAutoresizingMaskIntoConstraints = false
self.titleLabel!.backgroundColor = UIColor.gray
print(self.titleLabel!.text)
self.titleLabel!.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 15.0)
self.titleLabel!.centerYAnchor.constraint(equalTo: self.centerYAnchor)
self.addSubview(titleLabel!)
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.commonSetup()
setupViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonSetup()
}
override public func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.commonSetup()
}
var infoAttributed: NSAttributedString = NSAttributedString(string: "") {
didSet {
self.titleLabel?.attributedText = infoAttributed
setNeedsDisplay()
}
}
@IBInspectable var text: String = "RFC ..." {
didSet {
let stringWithAttribute = NSAttributedString(string: "text",
attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24.0)])
self.titleLabel?.text = "dsdsdsdsd"
}
}
}
在这部分中,我想使用NSAttributed
字符串格式化文本。但内容并未显示。我错过了什么?
var infoAttributed: NSAttributedString = NSAttributedString(string: "") {
didSet {
self.titleLabel?.attributedText = infoAttributed
setNeedsDisplay()
}
}
@IBInspectable var text: String = "RFC ..." {
didSet {
let stringWithAttribute = NSAttributedString(string: "text",
attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24.0)])
self.titleLabel?.text = "dsdsdsdsd"
}
}