簡體   English   中英

如何快速從另一個類訪問變量?

[英]How to get access to variable from another class in swift?

我的UserSearchController中有一個searchBar

class UserSearchController: UICollectionViewController, UICollectionViewDelegateFlowLayout,UISearchBarDelegate, UISearchDisplayDelegate {

lazy var searchBar: UISearchBar = {
    let sb = UISearchBar()
    sb.placeholder = "Search"
    sb.barTintColor = UIColor.gray
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.rgb(red: 230, green: 230, blue: 230, alpha: 1)
    sb.keyboardAppearance = .dark
    sb.delegate = self
    return sb
}()

我想從UserSearchCv中訪問並隱藏該搜索欄:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let user = filteredUsers[indexPath.item]
    print(user.username)

    let userProfileController = UserProfileController(collectionViewLayout: UICollectionViewFlowLayout())
    (superview?.next as? UIViewController)?.navigationController?.pushViewController(userProfileController, animated: true)

    UserSearchController.searchBar.isHidden = true //Something like this but it compiles an error
}

您需要通過對象引用而不是類名稱來訪問該變量。 嘗試這個-

userProfileController.searchBar.isHidden = true

你可以這樣做,我在這里傳遞數組。 但是您可以根據需要傳遞任何變量類型。

ShareViewController是您要推送的控制器,而arr_sticker是您要傳遞的任何變量。 請記住,傳遞變量和分配變量類型都是相同的。

   let SV = self.storyboard?.instantiateViewController(withIdentifier: "ShareViewController") as! ShareViewController
   SV.arr_sticker = arrm_symbols
   self.navigationController?.pushViewController(SV, animated: true)

在另一個控制器中,我像

    var arr_sticker = NSArray()

在此控制器中,當您print arr_sticker值時,您可以獲得從VC實際傳遞到此VC的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM