ios - 在具有框架问题的 iOS 中使用 swift 制作自定义 UILabel

标签 ios swift uilabel

我想使用 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/

相关文章:

ios - 为什么 Chrome for iOS 以不同方式处理 cookie?

ios - NSTimer 和 NSDateFormatter 麻烦。我的 timerLabel 刷新后消失了吗?

ios - 此iPad应用程序崩溃日志引用哪个线程?

IOS - 无法以编程方式打开 Whatsapp 聊天,但可以通过 HTML 进行

ios - 将 UILabel 文本与特定字符对齐

ios - 为什么我在 iOS 9.3.2 和 10.0.1 的 google-analytics 中出现 SSLError?

ios - URLSession 在 iOS 上使用自定义 CookieStorage?

swift - 根据用户的 Firebase 登录状态显示 View Controller

ios - 表格单元格中的突出显示模式

ios - 具有自动布局的多行UILabel,如何在不更改标签框架的情况下根据内容调整字体大小?