我想在另一个swift文件中创建一个通用函数,用于隐藏和显示带动画的UI对象。以下是两个代码:
func hide(object: /*My UI Object*/, duration: Double, delay: Double) {
UIView.animate(withDuration: duration, delay: delay, options: [], animations: {
object.alpha = 0
} ,
completion: nil
)
}
func show(object: /*My UI Object*/, duration: Double, delay: Double) {
UIView.animate(withDuration: duration, delay: delay, options: [], animations: {
object.alpha = 1
} ,
completion: nil
)
}
我想使用像UILabel,UIButton,UIView,UITextField等对象的这个函数。我找不到任何方式允许多种类型作为“对象”参数。
我也尝试将“object”的类型设置为Any,但这会导致“object”的错误没有成员“alpha”。
将类型设置为AnyObject会导致无法分配给属性的错误,因为“object”是“let”常量。
感谢您的帮助!
答案 0 :(得分:6)
您可以将参数键入为UIView
,因为所有提到的控件都是从它继承的。
func hide(object: UIView, duration: Double, delay: Double) {
UIView.animate(withDuration: duration, delay: delay, options: [], animations: {
object.alpha = 0
} ,
completion: nil
)
}
func show(object: UIView, duration: Double, delay: Double) {
UIView.animate(withDuration: duration, delay: delay, options: [], animations: {
object.alpha = 1
} ,
completion: nil
)
}
答案 1 :(得分:1)
由于所有这些对象都继承自UIView,因此您可以使用UIView类型