假设函数myFunc(sender:NSObject)
获取并输入对象:
func myFunc(sender:NSObject){
if sender is UILabel {
println("i'm label")
}else{
println("i'm not!")
}
}
@IBAction func runMyFunc(sender: UIButton) {
myFunc(myLabel)
}
我已将UIButton
,UIImage
和UILabel
与我的代码相关联:
@IBOutlet var myLabel: UILabel!
@IBOutlet var myImage: UIImage!
@IBOutlet var myButton: UIButton!
myButton
运行runMyFunc()
以上功能运作良好,我正在尝试做的事情是这样的:
func myFunc(sender:NSObject){
if sender is UILabel {
sender.text = "i'm new lable"
}else{
sender.image = UIImage(named: "newImage.png")
}
}
但它不起作用,如何在发件人UILabel
时告诉编译器,将其转换为UILabel
?
答案 0 :(得分:3)
这应该有效:
if let tempLabel = sender as? UILabel {
tempLabel.text = "i am a label"
} else if let tempImageView = sender as? UIImageView {
tempImageView.image = UIImage(named: "newImage.png")
}