ios - 从另一个类访问 viewController 元素

标签 ios swift xcode uiviewcontroller uielement

我正在处理这个项目,但是 Storyboard的 View Controller 中的元素有问题,我想从另一个类更改它的属性! 我的第一种方法是在我的第二堂课中从 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])
    }

我的第二个方法是在我的第二个类中再次实例化整个 viewcontroller,它什么也不做。

    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 View 之一的背景。这是我所有的类(class)

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

所以这是我的委托(delegate)代码,但仍然没有:(

//
//  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
}

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

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
}

关于ios - 从另一个类访问 viewController 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47889561/

相关文章:

swift - tableview 最大宽度约束

swift - AKMIDI监听器 : ReceivedNoteOn unable to change UI Components

ios - 使用 UIWebView 显示 PDF 不起作用

javascript - 我应该在哪里保存我的 React-Native 应用程序的用户和密码值?

ios - CCAvenue: "Error!!! in decrypting application request"

ios - 将静态参数添加到 Swift 中的#selector

ios - 检测页面何时按下 tabBar 项

ios - InfoPlist.strings 与常量的 global.h

xcode - Facebook API 快速检索好友列表

html - 如何将文本输入区域保留在我的 WebView 底部