Swift:将NSObject转换为其他类型的UI对象

时间:2015-05-26 14:17:43

标签: ios swift

假设函数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)
}

我已将UIButtonUIImageUILabel与我的代码相关联:

@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

1 个答案:

答案 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")
}