使用Swift枚举作为视图标记号而不使用rawValue

问题描述 投票:1回答:2

我有一个整数枚举,我想用于viewWithTag(_:)数字,但它给我错误“无法将类型'viewTags'的值转换为预期的参数类型'Int'”,即使枚举和标签号都是在viewWithTag(_:)需要的是Int

这很简单,如果我使用rawValue属性,我可以让它工作,但这比我想要的更麻烦和麻烦。

enum viewTags: Int {
    case rotateMirroredBtn
    case iPhone6SP_7P_8P
    case iPhoneX_Xs
    case iPhoneXs_Max
    case iPhone_Xr
    case unknown
}

// error on if statement "Cannot convert value of type 'viewTags' to expected argument type 'Int'"
if let tmpButton = self.view.viewWithTag(viewTags.rotateMirroredBtn) as? UIButton { 
    tmpButton.removeFromSuperview()
}
swift cocoa-touch enums viewwithtag
2个回答
2
投票

您可以在UIView上轻松添加扩展程序,为您进行转换。您只需要使用泛型参数将参数限制为可以从中获取Int的参数。

extension UIView
{
    /**
     Returns the view’s nearest descendant (including itself) whose `tag`
     matches the raw value of the given value, or `nil` if no subview
     has that tag.
     - parameter tag: A value that can be converted to an `Int`.
     */
    func firstView <Tag : RawRepresentable> (taggedBy tag: Tag) -> UIView?
        where Tag.RawValue == Int
    {
        let intValue = tag.rawValue
        return self.viewWithTag(intValue)
    }
}

约束T : RawRepresentable where T.RawValue == Int可以通过你的Int支持的枚举来实现。

非通用形式也很容易:func firstView(taggedBy viewTag: ViewTag) -> UIView?

奖金,您还可以添加一种方法,将“组合”值的原始值应用于视图:

func applyTag <Tag : RawRepresentable> (_ tag: Tag)
    where Tag.RawValue == Int
{
    self.tag = tag.rawValue
}

(不幸的是,没有办法把它写成属性,例如var composedTag: Tag where Tag : RawRepresentable, Tag.RawValue == Int,因为计算属性不能像方法一样创建自己的通用上下文。)


0
投票

你唯一遗漏的是rawValue。用viewTags.rotateMirroredBtn替换viewTags.rotateMirroredBtn.rawValue,如下所示:

if let tmpButton = self.view.viewWithTag(viewTags.rotateMirroredBtn.rawValue) as? UIButton { 
    tmpButton.removeFromSuperview()
}
© www.soinside.com 2019 - 2024. All rights reserved.