Ios 在自定义视图类中使用UIImageView的正确方法
我想在自定义视图上使用Appealable协议中的方法Ios 在自定义视图类中使用UIImageView的正确方法,ios,swift,uiview,uiimageview,Ios,Swift,Uiview,Uiimageview,我想在自定义视图上使用Appealable协议中的方法 protocol Appearable { } extension Appearable where Self: UIView { func appear(duration: Double, delay: Double) { self.alpha = 0 UIView.animate(withDuration: duration, delay: delay, options: .curveEa
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 {}
在我的主视图中,我创建了一个变量,其中包含一个我想在屏幕上显示的图像
class MainView: UIView {
let randomView: CustomUIView = {
var image = CustomUIView()
image = UIImageView(image: myImage)
return image
}
此代码将不起作用,因为无法将“UIImageView”类型的值分配给“CustomView”类型。我的问题是,执行此类操作的正确方法是什么。为什么不创建CustomImageView类并遵守Appeable协议
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并遵守协议。明白了。再次感谢你。