简体   繁体   中英

How to get access to variable from another class in swift?

I have a searchBar in my UserSearchController :

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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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