如何从Swift中的appdelegate更改UIImageVIew?

时间:2014-10-11 11:51:44

标签: ios xcode swift uiimageview

我有问题。我尝试使用UIImageView函数从appDelegate更改NSNotificationCenter,但收到错误消息。当我使用didFinishLaunchingWithOptionsNSNotificationCenter函数更改此内容后,我得到Exc_Breakpoint

在AppDelegate中:

  var classView: ViewController!

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
       NSNotificationCenter.defaultCenter().addObserver(self, selector: "myFunction:" ....
 }

 func myFunction(note: NSNotofication){
      classView.myImageView.image = UIImage(named: "picture1") //Here get the crash
  }

如何正确调用并更改UIImageView的{​​{1}}?

提前致谢!

1 个答案:

答案 0 :(得分:0)

从视图控制器发布通知并在userInfo通知中传递imageView,并在app delegate中提取imageView并将图像设置为此类,

class ViewController: UIViewController{

  override func viewDidLoad() {
    let imageView = UIImageView(frame: view.bounds)
    self.view.addSubview(imageView)

    // post notification and pass imageview in userInfo

    NSNotificationCenter.defaultCenter().postNotificationName("MySetImageViewNotification", object: nil, userInfo: ["imageView": imageView])
  }
}

在app delegate中,你会观察到通知,提取imageview并将图像设置为这样,

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "setImageViewNotification:", name: "MySetImageViewNotification", object: nil)
    return true
  }

  func setImageViewNotification(note: NSNotification){
    let userInfo = note.userInfo as [String: UIImageView]
    let imageView = userInfo["imageView"]
    imageView?.image = UIImage(named: "image.png")
  }
}
相关问题