2017-08-29 69 views
0

我有一個搜索欄,我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 
} 
+0

這可能會幫助你。 https://stackoverflow.com/documentation/ios/434/passing-data-between-view-controllers/2520/using-the-delegate-pattern-passing-data-back#t=201708291155386938448 –

+0

UserSearchController()。searchBar .isHidden = true'應該編譯,因爲它正在創建控制器的一個實例。你這樣做的方式是在UserSearchController類本身,而不是類的一個實例。您需要對「UserSearchController」實例的引用。 –

+0

你是否在UserSearchCv中聲明瞭UserSearchController的實例?使用該實例 – 3stud1ant3

回答

0

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

userProfileController.searchBar.isHidden = true 
+0

是的,我也這樣做了,但它編譯成一個錯誤 –

+0

不知道,除非'UserProfileController'具有搜索欄屬性,否則不會編譯。在這個問題中,只有'UserSearchController'有一個搜索欄屬性。 –

+0

@this不會編譯錯誤,但搜索欄不會消失。這就像我無法修改搜索欄 –

0

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

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值。

相關問題