简体   繁体   English

如何快速从另一个类访问变量?

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

I have a searchBar in my UserSearchController : 我的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
}()

And I want to access and hide that search bar from the UserSearchCv: 我想从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
}

You need to access that variable by object reference instead of class name. 您需要通过对象引用而不是类名称来访问该变量。 try this- 尝试这个-

userProfileController.searchBar.isHidden = true

You can do like that I am passsing array here. 你可以这样做,我在这里传递数组。 But you can pass any variable type as you want. 但是您可以根据需要传递任何变量类型。

ShareViewController is your controller to push, and arr_sticker is your any varibale to pass. ShareViewController是您要推送的控制器,而arr_sticker是您要传递的任何变量。 Remember both passing variable and assigning variable type would be same. 请记住,传递变量和分配变量类型都是相同的。

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

In another controller I have decalred array like 在另一个控制器中,我像

    var arr_sticker = NSArray()

In this controller when You print value of arr_sticker you can get value you actually passed from VC to this VC. 在此控制器中,当您print arr_sticker值时,您可以获得从VC实际传递到此VC的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM