访问视图来自另一个类的Controller元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了访问视图来自另一个类的Controller元素相关的知识,希望对你有一定的参考价值。

有这个项目即时工作,但我的故事板的viewcontroller中的元素有一个问题,我想从另一个类更改其属性!我的第一个方法是在我的第二个类中从viewcontroller实例化一个对象!在运行时返回nil!

        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        let mainstampvc = MainStampVc().storyboard?.instantiateViewController(withIdentifier: "mainstampvc") as? MainStampVc
//        mainstampvc?.setstampimage(imageURL: list_images[indexPath.row])

        let msvc = mainstampvc()
        mainstampvc?.setstampimage(imageURL: list_images[indexPath.row])
    }

我的第二种方法是在我的第二个类中再次实例化整个视图控制器,它什么都不做。

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let mainstampvc = MainStampVc().storyboard?.instantiateViewController(withIdentifier: "mainstampvc") as? MainStampVc
    mainstampvc?.setstampimage(imageURL: list_images[indexPath.row])
}

我想要的是当我点击我的uicollectionviewcell更改我的一个MainViewcontroller视图的背景时。这是我所有的课程

viewcontroller.swift

import Foundation
import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var stampholder: UIView!
    @IBAction func TextViewButton(_ sender: Any) {
        removerSubViews()
        addSubView(ViewName: "text")
    }
    @IBAction func AViewButton(_ sender: Any) {
        removerSubViews()
        addSubView(ViewName: "mohr")
    }
    @IBAction func BorderViewButton(_ sender: Any) {
    }
    @IBAction func DlViewButton(_ sender: Any) {
    }
    @IBOutlet weak var holderView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        addSubView(ViewName: "mohr")
        let mainstampvc = self.storyboard?.instantiateViewController(withIdentifier: "mainstampvc")
        let mainstampview = mainstampvc?.view
        mainstampview?.frame = stampholder.frame
        stampholder.addSubview((mainstampview)!)
    }
    func removerSubViews(){
            for view in self.holderView.subviews{
                view.removeFromSuperview()
            }
    }
    func addSubView(ViewName: String)
    {
        if let subview = Bundle.main.loadNibNamed(ViewName, owner: self, options: nil)?.first as? UIView {
            self.holderView.addSubview(subview);
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

mohrcollectionview.swift

import Foundation
import UIKit

class MohrCollectionViewController: UIView,UICollectionViewDataSource,UICollectionViewDelegate{
    var mohrPath: String = ""
    var fileManager: FileManager!
    var list_images : [String] = []
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fileManager = FileManager.default
        let currentDir = Bundle.main.resourcePath
        mohrPath = currentDir!
        let mohrsPath = try? fileManager.contentsOfDirectory(atPath: mohrPath + "/mohr")
        list_images = mohrsPath!
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return list_images.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        collectionView.register(UINib(nibName: "mohrcell", bundle: nil), forCellWithReuseIdentifier: "mohrcell")
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mohrcell", for: indexPath) as! mohrCellController
        let image = UIImage(named: list_images[indexPath.row])
        cell.cellimage.image = image
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let mainstampvc = MainStampVc().storyboard?.instantiateViewController(withIdentifier: "mainstampvc") as? MainStampVc
        mainstampvc?.setstampimage(imageURL: list_images[indexPath.row])
    }

}

mainstampvc.swift

import Foundation
import UIKit

class MainStampVc: UIViewController{


    @IBOutlet weak var stampimage: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        setstampimage(imageURL: "golbanafsh.png")
    }
    public func setstampimage(imageURL: String)
    {
        stampimage.image = UIImage(named: imageURL)
    }
}

任何帮助,将不胜感激

2

所以这是我的代码与代表团但仍然没有:(

//
//  MohrCollectionViewController.swift
//  Mohrem
//
//  Created by shayan rahimian on 12/18/17.
//  Copyright © 2017 shayan rahimian. All rights reserved.
//
import Foundation
import UIKit



class MohrCollectionViewController: UIView,UICollectionViewDataSource,UICollectionViewDelegate,UpdateBackgroundDelegate{
    var updatedelegate:UpdateBackgroundDelegate? = nil
    func updateBackground(imageURL: String) {
        print("mohr update back ground e balaE")
        if updatedelegate == nil {
            print("no delegate")
        }else{
            updatedelegate?.updateBackground(imageURL: imageURL)
        }
    }
    var mohrPath: String = ""
    var fileManager: FileManager!
    var list_images : [String] = []
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fileManager = FileManager.default
        let currentDir = Bundle.main.resourcePath
        mohrPath = currentDir!
        let mohrsPath = try? fileManager.contentsOfDirectory(atPath: mohrPath + "/mohr")
        list_images = mohrsPath!
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return list_images.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        collectionView.register(UINib(nibName: "mohrcell", bundle: nil), forCellWithReuseIdentifier: "mohrcell")
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mohrcell", for: indexPath) as! mohrCellController
        let image = UIImage(named: list_images[indexPath.row])
        cell.cellimage.image = image
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.updateBackground(imageURL: list_images[indexPath.row])
    }

}



//
//  MainStampvc.swift
//  Mohrem
//
//  Created by shayan rahimian on 12/19/17.
//  Copyright © 2017 shayan rahimian. All rights reserved.
//

import Foundation
import UIKit

protocol UpdateBackgroundDelegate : class {
    func updateBackground(imageURL: String)
}
class MainStampVc: UIViewController{

    @IBOutlet weak var stampimage: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        updateBackground(imageURL: "biggolabi.png")

    }
    func updateBackground(imageURL: String) {
        // update your background in this funcion
        print("extension")
        print(imageURL)
        stampimage.image = UIImage(named: imageURL)
    }

}

我做错了什么?

答案

您可以在构造它时将UIViewController引用传递给MohrCollectionViewController(您应该调用此MohrCollectionView以避免混淆)。然后,无论何时需要更新背景,都可以在参考上调用相关函数。

class ViewController : UIViewController {
    ...
    override func viewDidLoad() {
        ...
        let view = addSubView(ViewName: "mohr")
        view?.vc = self
    }
    func addSubView(ViewName: String) -> UIView?
    {
        if let subview = Bundle.main.loadNibNamed(ViewName, owner: self, options: nil)?.first as? UIView {
            self.holderView.addSubview(subview);
            return subview
        }
    }
    return nil
}

class MohrCollectionView {

     func updateVcBackground() {
         vc?.updateBackground()
     }
     var vc : ViewController? = nil
}

更简洁的方法是使用委托。委托使用协议来定义两个类之间的接口。

protocol UpdateBackgroundDelegate : class {
    func updateBackground()
}

class ViewController : UIViewController, UpdateBackgroundDelegate {
    ...
    override func viewDidLoad() {
        ...
        let view = addSubView(ViewName: "mohr")
        view?.updateBackgroundDelegate = self
    }
    func updateBackground() {
        // update your background in this funcion
    }
}

class MohrCollectionView {

     func updateVcBackground() {
         updateBackgroundDelegate?.updateBackground()
     }
     var updateBackgroundDelegate : UpdateBackgroundDelegate? = nil
}
另一答案

为使代表工作,请执行以下操作:

  1. 首先在Collection View Class中声明委托 protocol UpdateBackgroundDelegate : class { func updateBackground(imageURL: String) }
  2. 创建一个变量 var updateDelegate: UpdateBackgroundDelegate?

并将其粘贴到您想要触发更改背景颜色的collectionView类下面

  1. 在集合视图选择委托中,添加此行代码 updateDelegate.updateBackground(imageUrl: yourUrl)
  2. 在必须进行颜色更改的视图中,创建collectionView实例并添加此行代码 collectionView.updateDelegate = self
  3. 最后添加此扩展名 class ViewController :UpdateBackgroundDelegate { func updateBackground(imageUrl: yourUrl) { //write code to load image from url } }

以上是关于访问视图来自另一个类的Controller元素的主要内容,如果未能解决你的问题,请参考以下文章

如何以编程方式调用View Controller?

使用来自另一个类的实例访问有状态小部件的变量时,在 null 上调用 getter 长度

从另一个视图控制器访问常量

如何从另一个类(java)访问主类的变量?

jQuery .prepend() 使用来自另一个元素的类,如果它以特定单词开头

基于 Django 类的视图加载另一个带有数据的表单