我正在尝试制作一个“标签工厂”,帮助我为项目制作标签。
我有一个功能
getLabel(of type: LabelTypeEnum,
_ labelTitle: String? = nil,
_ textColor: UIColor? = nil,
_ textAlignment: NSTextAlignment? = nil) -> Label
然后我想用任意数量的参数调用它,例如:
getLabel(of: .myLabel, .center)
导致错误:“输入'字符串?'没有会员'中心'“
如何告诉编译器.center不是labelTitle属性?
我尝试通过添加“alignment:.center”来指定内容,但它强制我删除它。
如果有任何帮助,我会参考下面代码的上下文。
static func getLabel(of type: LabelType,
_ labelTitle: String? = nil,
_ textColor: UIColor? = nil,
_ textAlignment: NSTextAlignment? = nil) -> Label {
switch type {
case .regular:
return RegularLabel(labelTitle, textColor, textAlignment)
case .title:
return TitleLabel(labelTitle, textColor, textAlignment)
case .description:
return DescriptionLabel(labelTitle, textColor, textAlignment)
case .header:
return HeaderLabel(labelTitle, textColor, textAlignment)
case .subHeader:
return SubHeaderLabel(labelTitle, textColor, textAlignment)
case .body:
return BodyLabel(labelTitle, textColor, textAlignment)
case .fatBody:
return FatBodyLabel(labelTitle, textColor, textAlignment)
case .smallGray:
return SmallGrayLabel(labelTitle, textColor, textAlignment)
}
}
标签初始
convenience init(_ title: String? = nil, _ color: UIColor? = nil, _ alignment: NSTextAlignment? = nil) {
self.init(frame: .zero)
self.text = title ?? self.text
self.textColor = color ?? self.textColor
self.textAlignment = alignment ?? self.textAlignment
}
许多电话之一
private lazy var titleLabel: UILabel = {
let label = LabelFactory.getLabel(of: .header, .center)
self.addSubview(label)
return label
}()
答案 0 :(得分:2)
这是因为方便而忽略参数标签的诅咒,这应该起作用:
getLabel(of type: LabelTypeEnum,
labelTitle: String? = nil,
textColor: UIColor? = nil,
textAlignment: NSTextAlignment? = nil) -> Label
getLabel(of: .myLabel, textAlignment: .center)