【问题标题】:How do I declare a public interface, such as apple does. Another way, hide the implementation如何声明一个公共接口,例如苹果公司。另一种方式,隐藏实现
【发布时间】:2014-06-06 06:14:26
【问题描述】:

就像 UILabel 类:

class UILabel : UIView, NSCoding {

    var text: String! // default is nil
    var font: UIFont! // default is nil (system font 17 plain)
    var textColor: UIColor! // default is nil (text draws black)
    var shadowColor: UIColor! // default is nil (no shadow)
    var shadowOffset: CGSize // default is CGSizeMake(0, -1) -- a top shadow
....
}

但是如果我定义一个这样的类,它也没有 init 函数。编译器会警告我。 我怎么能做和苹果一样的事情,隐藏实现,只声明接口。谢谢。

【问题讨论】:

标签: init swift


【解决方案1】:

UILabel 没有在 Swift 中实现。

您在此处看到的内容来自于 UILabel 的 Objective-C 头文件。

【讨论】:

    【解决方案2】:

    您应该仔细查看协议。你可以这样声明你的协议:

    protocol UIViewProtocol {
        var text: String { get }
        ...
    }
    

    稍后在您的课程中引用它:

    class MyClass : UIViewProtocol {
        ....
    }
    

    Apple 参考:iOS 8 Protocols

    【讨论】:

      【解决方案3】:

      尝试更改类名并尝试。

      class MyClass : UIView, NSCoding {
      
              var text: String! // default is nil
              var font: UIFont! // default is nil (system font 17 plain)
              var textColor: UIColor! // default is nil (text draws black)
              var shadowColor: UIColor! // default is nil (no shadow)
              var shadowOffset: CGSize // default is CGSizeMake(0, -1) -- a top shadow
              }
      

      【讨论】:

        猜你喜欢
        • 2021-10-22
        • 1970-01-01
        • 2011-10-08
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-13
        相关资源
        最近更新 更多