我想使用 swift 创建自己的自定义 UILabel,但在使用 init 父类(super class)时遇到了框架问题。
这是我之前的:
let label = UILabel()
我以前基本上使用普通的 UILabel。首先我的问题是,框架是如何设置的?因为当我进入 UILabel 类时,它继承自 UIView 并且 UIView 中的 init 方法采用了一个框架。那么这个框架是如何创建的呢?
然后这将我带到我自己的自定义 UILabel,我将其称为 TimeLabel。这是它的实现:
class TimeLabel: UILabel {
var clientName: String?
var time: Time?
init(name:String, time:Time) {
self.clientName = name
self.time = time
super.init(frame: ??)
}
required init?(coder aDecoder: NSCoder) {
super.init(frame:??)
}
}
这现在链接到第一个问题,我应该从哪里得到这个框架?我在调用 UILabel 之前没有提供框架?我该如何处理?
最佳答案
这是您设置类(class)的方式:
请记住使用“便利”关键字。通过使用 convenience 关键字,您不需要添加 UIVIew 继承的 NSCoding 协议(protocol)。
class TimeLabel: UILabel {
var clientName: String?
var time: Time?
// Use convenience keyword
convenience init(name: String?, time: Time?) {
self.init(frame: CGRect.zero)
self.clientName = name
self.time = time
}
}
这是根据内容获取宽度和高度的方法
1。从一行标签获取宽度和高度
let timeLabel = TimeLabel(name: "John", time: sometime)
let size = timeLabel.sizeThatFits(CGSize.zero)
// This is the label calculated width and height
let width = size.width
let height = size.height
2。从多行标签获取宽高
let timeLabel = TimeLabel(name: "John", time: sometime)
// To active multiline features, set numberOfLines to 0
timeLabel.numberOfLines = 0
let size = timeLabel.sizeThatFits(CGSize(width: putYourWidthHere, height: 0))
// This is the label calculated width and height
let width = size.width
let height = size.height
关于ios - 在具有框架问题的 iOS 中使用 swift 制作自定义 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908584/