我正在尝试将主视图 Controller 中的函数(func getCityWeatherData
)扩展到下面的类,该类仅在某些条件下显示设置的项目。
我还标记了具有一些选择条件的示例数据 - 如何将它们与通常的数组分开?我已经尝试过在 numberOfRowsAt
部分中在其他地方读到的内容,但我很困惑。
class ProductRecsTableViewController: UITableViewController {
//Mark: Properties
var products = [Product]()
override func viewDidLoad() {
super.viewDidLoad()
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if getCityWeatherData.humidity < 50 {
return productsHumidity.count
} else {
return products.count
} }
这是我创建的示例单元格 - 我想要“天气:...”,但要定义该项目的显示时间。
guard let prod1 = Product(name: "XXX", photo: photo1, rating: 1, weather: "Humidity")
最佳答案
听起来您正在尝试从 ProductRecsTableViewController
类访问名为 getCityWeatherData
的函数,除非两者之间存在某种类型的关系,否则您无法执行此操作 Controller 。您可以创建一个名为 ProductRecsTableViewControllerDelegate: AnyObject
的协议(protocol),该协议(protocol)具有单个函数,可将您需要的信息返回到 ProductRecsTableViewController
。无论哪种方式,听起来您只需要通过委托(delegate)或属性在两个 Controller 之间传递数据/信息。
更新:#2
class CustomViewController: UIViewController, CustomDelegate {
func askForData() -> Data {
return _whateverDataYouWant
}
}
protocol CustomDelegate: AnyObject {
func askForData() -> Data
}
class ProductRecsTableViewController: UITableViewController {
weak var delegate: CustomDelegate?
func myMethodThatNeedsAccessToData() {
let data = delegate?.askForData()
doStuffWith(data)
}
}
在此过程中的某个时刻,您需要在 ViewController
中说出 myProductsRectsTableViewController.delegate = self
关于Swift3:为条件单元格从主 VC 调用 func 数据到 TableVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45065377/