如何将数据传递给另一个类?

问题描述 投票:0回答:1

我使用此代码在两个类之间传递数据。我想通过

index
pageIndex
imagesArray
。我想在
SampleViewController 
加载时创建一个数组。我需要将图像从数组和
pageIndex
传递到ModelView类中的
configure(theData: PageData)
函数:

示例视图控制器:

class SampleViewController: UIViewController {
    
    var pagesData = [PageData]()
    var index = Int()
    var pageIndex: Int = -1
    var imageArray: [UIImage] = []
    let detailViewController = ModelView()
    let pageContainer: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    let pageViews: [ModelView] = {
        let view = [ModelView(), ModelView()]
        view[0].translatesAutoresizingMaskIntoConstraints = false
        view[1].translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
        
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadImages()
        
        pageContainer.addSubview(pageViews[0])
        pageContainer.addSubview(pageViews[1])
        view.addSubview(pageContainer)

        transitionAnimation(animated: false, direction: "fromRight")
    }
        
    func setupViews() {
        pageContainer.addSubview(pageViews[0])
        pageContainer.addSubview(pageViews[1])
        view.addSubview(pageContainer)
    }
    
    func loadData(fileName: Any) -> PagesData {
        var url = NSURL()
        
        switch index {
        case 0:
            url = Bundle.main.url(forResource: "\(index)", withExtension: "json")! as NSURL
            
        case _:
            let fileManager = FileManager.default
            let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
            let documentDirectoryURL: NSURL = (urls.first as NSURL?)!
            url = documentDirectoryURL.appendingPathComponent("/\(index)/text.json")! as NSURL
        }
        
        let data = try! Data(contentsOf: url as URL)
        let person = try! JSONDecoder().decode(PagesData.self, from: data)
        return person
    }
    
    func loadImages() {
        var images = [UIImage]()
        
        switch index {
        case 0:
            for imageIndex in 1...18 { images.append(UIImage(named: "\(imageIndex).jpg")!) }
            
        case _:
            let filemanager = FileManager.default
            let filesURL = URL.documentsDirectory.appendingPathComponent("\(index)")
            let numberOfJPGs = filemanager.enumerator(at: filesURL, includingPropertiesForKeys: nil)?
                .filter { ($0 as? URL)?.pathExtension.caseInsensitiveCompare("jpg") == .orderedSame }
                .count
            for myIndex in 0...numberOfJPGs! {
                let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
                let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
                let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
                let dirPath = paths.first
                let imageURL = URL(fileURLWithPath: dirPath!).appendingPathComponent("\(index)/images/\(myIndex).jpg")
                if let image = UIImage(contentsOfFile: imageURL.path) { imageArray.append(image) }
                detailViewController.index = index
                detailViewController.imageArray = imageArray
            }
        }
    }
        
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: view.self)
            if (location.x > self.view.frame.size.width - (view.safeAreaInsets.left * 1.5)) {
                transitionAnimation(animated: true, direction: "fromRight")
            } else if (location.x < (view.safeAreaInsets.left * 1.5)) {
                transitionAnimation(animated: true, direction: "fromLeft")
            }
        }
    }
    
    func transitionAnimation(animated: Bool, direction: String) {
        
        let result = loadData(fileName: pagesData)
        
        switch direction {
        case "fromRight":
            pageIndex += 1
        case "fromLeft":
            pageIndex -= 1
        default: break
        }
        
        if pageIndex <= -1 {
            
            pageIndex = 0
            
        } else if pageIndex >= result.pagesData.count {
            
            pageIndex = result.pagesData.count - 1
            
        } else {
            
            let fromView = pageViews[0].isHidden ? pageViews[1] : pageViews[0]
            let toView = pageViews[0].isHidden ? pageViews[0] : pageViews[1]
            toView.configure(theData: result.pagesData[pageIndex])

            if animated {
                
                toView.isHidden = false
                
                UIView.animate(withDuration: 1.0, animations: {
                    
                    let animation = CATransition()
                    animation.duration = 1.0
                    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
                    animation.isRemovedOnCompletion = true
                    animation.subtype = direction
                                        
                    let tapAnimationType = "fade"
                    
                    switch tapAnimationType {
                    case "pageCurl": animation.type = "pageCurl"
                    case "fade": animation.type = "fade"
                    case "moveIn": animation.type = "moveIn"
                    case "push": animation.type = "push"
                    case "reveal": animation.type = "reveal"
                    default: animation.type = "fade" }
                    
                    self.pageContainer.layer.add(animation, forKey: "pageAnimation")
                    self.pageContainer.bringSubview(toFront: toView)
                })
                
            } else {
                fromView.isHidden = true
                toView.isHidden = false
            }
        }
    }
    
    detailViewController.pageIndex = pageIndex
}

模型视图:

class ModelView: UIView {
    
    var textPosition = ""
    let textLabel = UILabel()
    let imageView = UIImageView()
    var index = Int()
    var pageIndex = Int()
    var imageArray: [UIImage] = []
        
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    
    func commonInit() {
        setupViews()
    }
        
    func setupViews() {
        addSubview(imageView)
        addSubview(textLabel)
    }
    
    func configure(theData: PageData) {
        textLabel.text = theData.textData
        textPosition = theData.textPosition
        textLabel.textColor = UIColor(theData.textColor)
        textLabel.layer.shadowColor = UIColor(theData.shadowColor).cgColor
        imageView.image = imageArray[pageIndex]
    }

但是在 ModelView 中我的图像数组是空的。但是

index
pageIndex
通过了并且工作正常。应用程序在这一行崩溃了
imageView.image = imageArray[pageIndex]
并出现以下错误:索引超出范围

如何解决?

swift
1个回答
0
投票

加载图像完成后,需要为每个ModelView分配imageArray。

func loadImages() {
        var images = [UIImage]()
        
        switch index {
        case 0:
            for imageIndex in 1...18 { images.append(UIImage(named: "\(imageIndex).jpg")!) }
            
        case _:
            let filemanager = FileManager.default
            let filesURL = URL.documentsDirectory.appendingPathComponent("\(index)")
            let numberOfJPGs = filemanager.enumerator(at: filesURL, includingPropertiesForKeys: nil)?
                .filter { ($0 as? URL)?.pathExtension.caseInsensitiveCompare("jpg") == .orderedSame }
                .count
            for myIndex in 0...numberOfJPGs! {
                let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
                let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
                let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
                let dirPath = paths.first
                let imageURL = URL(fileURLWithPath: dirPath!).appendingPathComponent("\(index)/images/\(myIndex).jpg")
                if let image = UIImage(contentsOfFile: imageURL.path) { images.append(image) }
                detailViewController.index = index
                detailViewController.imageArray = images
            }
        }
        // Set imageArray here
        pageViews.forEach { view in
            $0.imageArray = images
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.