【问题标题】:Proper way to use UIImageView inside a custom View class在自定义 View 类中使用 UIImageView 的正确方法
【发布时间】:2017-03-18 19:19:58
【问题描述】:

我想在我的自定义视图上使用 Appearable 协议中的方法。

protocol Appearable { }

extension Appearable where Self: UIView { 

    func appear(duration: Double, delay: Double) {
        self.alpha = 0

        UIView.animate(withDuration: duration, delay: delay, options: .curveEaseIn, animations: {
            self.alpha = 1
            self.transform = CGAffineTransform(scaleX: 2.0, y: 1.5)
        }, completion: nil)

        self.transform = CGAffineTransform.identity
    }
}

我的自定义视图:

class CustomView: UIView, Appearable {}

在我的 MainView 中,我创建了一个带有我想在屏幕上显示的图像的变量。

class MainView: UIView {
    let randomView: CustomUIView = {
    var image = CustomUIView()
    image = UIImageView(image: myImage)

    return image
}

此代码将不起作用,因为无法将“UIImageView”类型的值分配给“CustomView”类型。我的问题是,进行这种操作的正确方法是什么。

【问题讨论】:

    标签: ios swift uiview uiimageview


    【解决方案1】:

    为什么不创建一个 CustomImageView 类并遵守 Appearable 协议?

    class CustomImageView: UIImageView, Appearable {}
    

    现在你可以做你需要的:

    let imageView = CustomImageView()
    imageView.image = myImage
    

    并使用默认协议方法:

    imageView.appear(duration: 2.0, delay: 0.0)
    

    【讨论】:

    • 感谢您的回答。它确实有效。但是我会从 UIView 继承什么 id 然后做同样的事情?有比将图像投射到我的自定义类更好的选择吗?
    • @Billy 您尝试将使用您的协议扩展的 UIView 转换为 UIImageView。 UIImageView 扩展了 UIView,它已经调整了 API,不适合做这样的转换。如果您希望在 UIImageView 类上调用您的协议方法,请自定义 UIImageClass 并符合协议。
    • 知道了。再次感谢您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多