如何在swift中从另一个类访问变量?
我有一个搜索栏,我UserSearchController:如何在swift中从另一个类访问变量?
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
是的,我也这样做了,但它编译成一个错误 –
不知道,除非'UserProfileController'具有搜索栏属性,否则不会编译。在这个问题中,只有'UserSearchController'有一个搜索栏属性。 –
@this不会编译错误,但搜索栏不会消失。这就像我无法修改搜索栏 –
你可以这样做 我在这里传递数组。但是,您可以根据需要传递任何变量类型。 ShareViewController
是你的控制器推动,而是你的任何varibale通过。记住传递变量和赋值变量类型都是一样的。
let SV = self.storyboard?.instantiateViewController(withIdentifier: "ShareViewController") as! ShareViewController
SV.arr_sticker = arrm_symbols
self.navigationController?.pushViewController(SV, animated: true)
在另一个控制器我已经decalred阵列状
var arr_sticker = NSArray()
在此控制器时,您的print
值,你可以得到你真正从VC传递给这个VC值。
这可能会帮助你。 https://stackoverflow.com/documentation/ios/434/passing-data-between-view-controllers/2520/using-the-delegate-pattern-passing-data-back#t=201708291155386938448 –
UserSearchController()。searchBar .isHidden = true'应该编译,因为它正在创建控制器的一个实例。你这样做的方式是在UserSearchController类本身,而不是类的一个实例。您需要对“UserSearchController”实例的引用。 –
你是否在UserSearchCv中声明了UserSearchController的实例?使用该实例 – 3stud1ant3