繁体   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