ios - 给定枚举作为参数,如何从 func 返回不同的 uibutton 子类?

标签 ios swift generics casting

所以下面我包含了一些我的代码。这段代码显然无法编译。当我尝试将我的子类类型转换为 UIButton 类型时,错误显示为 Expected member name or constructor call after type name

我希望能够在我的 AppDelegate 中调用此按钮功能,以便我可以更改该类型的 UIAppearance。这就是我返回类型而不是实例的原因。因此,如果我不能使用强制转换,我应该尝试使用泛型,还是我对这个问题的思考完全错误?任何见解表示赞赏。无论如何,我只想知道如何选择特定类型的按钮,以便我可以设置它的样式,无论是否有办法使用泛型或强制转换。

enum BtnType : Int {
    case Primary
    case Secondary
}

func button(type: BtnType) -> UIButton.Type {
    var button: UIButton.Type

    switch type {
        case .Primary:
            button = PrimaryButton.Type as! UIButton.Type
        case .Secondary:
            button = SecondaryButton.Type as! UIButton.Type
        default:
            button = PrimaryButton.Type as! UIButton.Type
    }

    return button
}

最佳答案

在您的自定义按钮类型上使用 self 以返回相应的元类型(类型为 Button.Type):

func buttonType(for type: BtnType) -> UIButton.Type {
    let button: UIButton.Type
    switch type {
    case .Primary: button = PrimaryButton.self
    case .Secondary: button = SecondaryButton.self
    }
    return button
}

请注意,您可以说 let button: UIButton.Type(而不是 var),因为它在 switch 中设置了一次。

另请注意,您不需要将 转换为! UIButton.Type 因为 AnyButtonSubclass.self 是一个 UIButton.Type

示例用法:

let b = buttonType(for: .Primary).init(type: .system) // b is a UIButton
b.setTitle("Primary", for: .normal)

关于.Type.self

(我在这里只讨论类,不讨论编译时类型与运行时类型,以使事情更简单。)

您可能习惯于使用对象和类。对象是类的实例。对象的类型是对象所属的类。更高一级(因此是元), 您正在处理类和元类。这里,类的类型是它的元类。

在句法上,无论何时你需要或想要写一个类型,你都可以说Foo.Type。这可以是变量的类型、参数的类型,或者在本例中,buttonType(for:) 的返回类型。 UIButton.selfUIButton.Type 类型的表达式。就像您可以将 UIButton 实例分配给 UIButton 类型的变量一样,您可以将 UIButton.self 分配给 UIButton 的变量.键入

请注意,在两个级别(对象和类、类和元类)上,您都具有“is-a”关系。您可以将 UIButton 的任何子类的实例分配给 UIButton 类型的变量。 同样,您可以将任何 SubclassOfUIButton.self 分配给 UIButton.Type 的变量。

一些很有希望的说明性代码:

class PrimaryButton: UIButton { ... }
class SecondaryButton: UIButton { ... }

let button = PrimaryButton(type: .system)
button is PrimaryButton  // true
button is UIButton  // true
button is UIControl  // true
// etc
button is String  // false
let uibutton: UIButton = button

let buttonType: PrimaryButton.Type = PrimaryButton.self
buttonType is PrimaryButton.Type  // true
buttonType is UIButton.Type  // true
buttonType is UIControl.Type  // true
// etc
buttonType is String.Type  // false
let uiButtonType: UIButton.Type = buttonType

关于ios - 给定枚举作为参数,如何从 func 返回不同的 uibutton 子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43019404/

相关文章:

c# - 具有泛型类型约束的泛型方法的尴尬语法

generics - 为什么字符串和数字有单独的比较函数/运算符?

ios - 可以 renderInContext : maintain corner radius and shadows?

ios - 如何在 swift 3 中将 NsArraym 设置为 NSString

iOS-charts雷达图删除标签并用颜色填充网络

objective-c - 将可选的 JSON 从 react-native 传递给 Swift

iOS 自定义 slider 删除两端的最小和最大空间

iphone - 我可以在Windows上运行Objective C应用程序吗?

ios - 一秒钟后如何快速更改字符串?

java - 通用返回类型上限 - 接口(interface)与类 - 令人惊讶的有效代码