gpt4 book ai didi

ios - 将更多数据嵌入到枚举案例中

转载 作者:行者123 更新时间:2023-11-28 12:54:17 26 4
gpt4 key购买 nike

我有以下叠层枚举。

public enum Icons {
public enum Arrow: String {
case Angle1 = "\u{f100}"
case Angle2 = "\u{f101}"
case Angle3 = "\u{f102}"
case Angle4 = "\u{f103}"
case ArrowBottomLeft = "\u{f104}"
case ArrowBottomRight = "\u{f105}"
}

public enum Clothing: String {
case BallCap = "\u{f100}"
case Belt = "\u{f101}"
case Boot = "\u{f102}"
case BowTie = "\u{f103}"
}

public enum Emotions: String {
case Angel = "\u{f100}"
case AngrySick = "\u{f101}"
case Angry = "\u{f102}"
case Bitter = "\u{f103}"
case Concerned = "\u{f104}"
case Cool = "\u{f105}"
}
}

我有大量图标,我想将它们集成到我的应用程序中。我还有一个 UIImage 扩展初始化程序,它采用 UIFont 作为参数和要绘制的图标的字符串(源自 Icons.Category.Icons - 请注意,在这种情况下,Category 是 Arrow、Clothing 或情绪)。

要获取图标,我调用:

let image = UIImage(  
fromIcon: Icons.Emotions.Angel.rawValue,
withFont: UIFont.iconFontAngel(22)
)

三种类型的图标中的每一种都有一个关联的 UIFont 扩展:

  • 箭头类型有 UIFont.iconFontArrow(size)
  • 服装类型有UIFont.iconFontClothing(size)
  • 情绪类型有 UIFont.iconFontEmotions(size)

我怎样才能更好地声明图标以包括 UIFont、字体大小和其他特定于类别的选项,因为我确切地知道每个类别对应的 UIFont 并且我只需要传递一个参数,例如 Icons。 Arrow.Angle3 到 UIImage 初始值设定项并从此参数类型中提取字符串、UIFont 和其他需要的选项?

我正在考虑将图标类型声明为已设置,但我不确定如何以干净的方式解决这个问题。

最佳答案

不要为此使用枚举。使用结构。

public struct FontBasedIcon {

private init(string: String, fontName: String) {
self.string = string
self.fontName = fontName
}

public let string: String
public let fontName: String

public func font(size size: CGFloat) -> UIFont {
return UIFont(name: fontName, size: size)!
}

public func image(fontSize fontSize: CGFloat) -> UIImage {
let string = self.string as NSString
let attributes = [ NSFontAttributeName: self.font(size: fontSize) ]
var rect = string.boundingRectWithSize(CGSizeMake(CGFloat.infinity, CGFloat.infinity), options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
let size = CGSizeMake(ceil(rect.width), ceil(rect.height))
UIGraphicsBeginImageContextWithOptions(size, false, 0)
defer { UIGraphicsEndImageContext() }
string.drawAtPoint(CGPoint.zero, withAttributes: attributes)
return UIGraphicsGetImageFromCurrentImageContext()
}

}

然后将常量声明为静态属性:

public extension FontBasedIcon {
public struct Arrow {
public static let Angle1 = FontBasedIcon(string: "\u{f100}", fontName: "ArrowFont")
public static let Angle2 = FontBasedIcon(string: "\u{f101}", fontName: "ArrowFont")
// etc.
}

public struct Emotion {
public static let Angel = FontBasedIcon(string: "\u{f100}", fontName: "EmotionFont")
public static let AngrySick = FontBasedIcon(string: "\u{f101}", fontName: "EmotionFont")
// etc.
}
}

用法:

let angelImage = FontBasedIcon.Emotion.Angel.image(fontSize: 22)

关于ios - 将更多数据嵌入到枚举案例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35440086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com