【问题标题】:Reusable UILabel styles in Swift, Xcode 6.4Swift、Xcode 6.4 中可重用的 UILabel 样式
【发布时间】:2015-08-13 13:03:56
【问题描述】:

有没有比创建覆盖 UILabel 的自定义类更简单的方法来设置 UILabel 的样式。目前我需要一堆不同字体大小和文本颜色的样式。

【问题讨论】:

  • 在标准UILabel 上设置fonttextColor 属性有什么问题?
  • 您的意思是使用界面生成器单独在每个 UILabel 上?
  • 嗯,你的问题没有提到 IB。这些属性显然需要在代码中应用。或者,您可以尝试UIAppearance 协议。然而,它在 Swift 中是有限的。

标签: ios swift xcode6 uilabel xcode6.4


【解决方案1】:

我不知道这是一个好习惯......但你可以这样:

extension UILabel {
    @IBInspectable var myStyle: String {
        set {
            switch newValue  {
            case "style1":
                self.font = UIFont.systemFontOfSize(17)
                self.textColor = UIColor.blackColor()

            case "style2":
                self.font = UIFont.boldSystemFontOfSize(32)
                self.textColor = UIColor.redColor()

            default:
                break
            }
        }
        get {
            return ""
        }
    }
}


也许,您应该使用@IBDesignable 定义一个子类。因为这在 IB 中显示了更好的预览。并且,您可以使用Editor > Size To Fit 或IB 中的自动布局功能。

@IBDesignable class StyledLabel: UILabel {
    @IBInspectable var myStyle: String = "" {
        didSet {
            switch self.myStyle {
            case "style1":
                self.font = UIFont.systemFontOfSize(17)
                self.textColor = UIColor.blackColor()
            case "style2":
                self.font = UIFont.boldSystemFontOfSize(32)
                self.textColor = UIColor.redColor()
            default:
                break
            }
        }
    }
}

【讨论】:

  • 这正是我想要的!现在我只需要知道这是否是好的做法
  • 这个问题的重点是避免使用自定义类,因为我想避免为我的所有 UILabel 设置自定义类:).. 预览不如编写更少的代码重要,所以现在我'会坚持你在编辑前写的内容
  • 第二个选项(上课)我测试过,真的很棒。现在我可以根据需要更改自定义 UI 的类名和样式。真的很有帮助。
猜你喜欢
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多