Swift - 从另一个函数访问 UIView 的实例

Posted

技术标签:

【中文标题】Swift - 从另一个函数访问 UIView 的实例【英文标题】:Swift - access instance of UIView from another function 【发布时间】:2019-12-03 21:59:15 【问题描述】:

在我的项目中,用户可以像这样创建UIView(“CustomWishlistView”):

func createCustomWishlistView() -> CustomWishlistView 
    let v = CustomWishlistView()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.backgroundColor = .darkGray
    v.layer.cornerRadius = 30
    return v


@IBAction func createListButtonTapped(_ sender: Any) 


    // "Liste erstellen" button was tapped
    self.appDidEnterBackgroundHandler()

    if let txt = listNameTextfield.text 

        self.newListTextfield.resignFirstResponder()

        // append user-entered text to the data array
        self.theData.append(txt)
        self.imageData.append(self.image!)

        let theCustomWishlistView = createCustomWishlistView()

        self.view.addSubview(theCustomWishlistView)
        // constrain CustomWishlistView
        theCustomWishlistView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 120.0).isActive = true
        theCustomWishlistView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
        theCustomWishlistView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 30.0).isActive = true
        theCustomWishlistView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -30.0).isActive = true
        theCustomWishlistView.wishlistImage.image = self.image
        theCustomWishlistView.wishlistLabel.text = txt
        theCustomWishlistView.transform = CGAffineTransform(translationX: 0, y: 1000)

        self.view.bringSubviewToFront(containerView)


        // reload the collection view
        theCollectionView.reloadData()
        theCollectionView.performBatchUpdates(nil, completion: 
            (result) in
            // scroll to make newly added row visible (if needed)
            let i = self.theCollectionView.numberOfItems(inSection: 0) - 1
            let idx = IndexPath(item: i, section: 0)
            self.theCollectionView.scrollToItem(at: idx, at: .bottom, animated: true)

            // close (hide) the "New List" view
            self.closeButtonTappedNewList(nil)
        )
    

transform 那个 view 所以一开始它是不可见的。它应该在用户单击UICollectionView 内的cell 后出现。我的代码(在cellForItemAt 内)如下所示:

    if indexPath.item <= theData.count 
           let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContentCell", for: indexPath) as! ContentCell

            cell.testLabel.text = theData[indexPath.item - 1]

            cell.buttonView.setImage(imageData[indexPath.item - 1], for: .normal)

        cell.customWishlistTapCallback = 
            // let CustomWishlistView appear
//            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: 
//                theCustomWishlistView.transform = CGAffineTransform(translationX: 0, y: 0)
//            )
            // let welcomeText disappear
            UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: 
                self.welcomeTextLabel.transform = CGAffineTransform(translationX: 0, y: 0)
            )
        
           return cell
       

我的问题是我不能让我的customWishlistView 出现,因为我无法访问它。有没有办法解决这个问题? :)

【问题讨论】:

您需要将theCustomWishlistView 设为实例变量 我该怎么做?对不起,我只是一个初学者 【参考方案1】:

您需要将theCustomWishlistView 设为如下实例变量。您没有显示整个类代码,所以我的解决方案是尽可能完整的,而无需查看您的其余代码

class CustomViewController: UIViewController, UICollectionViewDataSource 

    var theCustomWishlistView: UIView?

    func createCustomWishlistView() -> CustomWishlistView 
        let v = CustomWishlistView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .darkGray
        v.layer.cornerRadius = 30
        return v
    

    @IBAction func createListButtonTapped(_ sender: Any) 

        // "Liste erstellen" button was tapped
        self.appDidEnterBackgroundHandler()

        if let txt = listNameTextfield.text 

            self.newListTextfield.resignFirstResponder()

            // append user-entered text to the data array
            self.theData.append(txt)
            self.imageData.append(self.image!)

            let wishlistView = createCustomWishlistView()

            self.view.addSubview(wishlistView)
            // constrain wishlistView
            wishlistView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 120.0).isActive = true
            wishlistView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
            wishlistView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 30.0).isActive = true
            wishlistView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -30.0).isActive = true
            wishlistView.wishlistImage.image = self.image
            wishlistView.wishlistLabel.text = txt
            wishlistView.transform = CGAffineTransform(translationX: 0, y: 1000)

            // retain wishlist view in instance variable
            self.theCustomWishlistView = wishlistView
            self.view.bringSubviewToFront(containerView)

            // reload the collection view
            theCollectionView.reloadData()
            theCollectionView.performBatchUpdates(nil, completion: 
                (result) in
                // scroll to make newly added row visible (if needed)
                guard let i = self.theCollectionView.numberOfItems(inSection: 0) else  return 
                let idx = IndexPath(item: i - 1, section: 0)
                self.theCollectionView.scrollToItem(at: idx, at: .bottom, animated: true)
                // close (hide) the "New List" view
                self.closeButtonTappedNewList(nil)
            )

        
    

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
        return theData.count
    

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 

       let _cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContentCell", for: indexPath)

        guard let cell = _cell as? ContentCell else  return _cell 

        cell.testLabel.text = theData[indexPath.item - 1]

        cell.buttonView.setImage(imageData[indexPath.item - 1], for: .normal)

        cell.customWishlistTapCallback = 
            // let CustomWishlistView appear
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: 
                self.theCustomWishlistView?.transform = CGAffineTransform(translationX: 0, y: 0)
            )
            // let welcomeText disappear
            UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: 
                self.welcomeTextLabel.transform = CGAffineTransform(translationX: 0, y: 0)
            )
        
       return cell
   


【讨论】:

您在编辑之前的回答实际上对我来说更有意义。您的答案现在不适用于我的代码。这是我的完整项目:github.com/chriskonnerth/Wishlist 这可能与滥用严格的可选包装器(!)有关,并且没有逐字复制我关于可选包装器的代码。但是,我回复了我的答案以坚持您使用可选包装器 您能否更新您的问题本身以包含您的视图控制器的所有代码? 我的ViewController 的代码非常混乱 :( 我无法真正简化它。我知道这是个坏问题,但我不知道还能做什么:/跨度> 我尝试实现您的答案,但它并没有真正按照应有的方式工作,因为它不会每次都为每个cell 创建一个新的View,而是总是覆盖旧的。我希望你能明白我的意思

以上是关于Swift - 从另一个函数访问 UIView 的实例的主要内容,如果未能解决你的问题,请参考以下文章

从另一个文件中的 SKScene 中删除 UIView

在 Swift 中从另一个 ViewController 访问变量

如何从另一个类访问 UIView 的宽度和高度?

如何在swift中按下按钮从另一个xib文件加载另一个xib文件

从另一个类访问 IBOutlet

从另一个类 Swift 访问 navigationItem.title