由于一些奇怪的原因,没有调用collectionView。我把断点放在numberOfItemsInSection和cellForItemAtIndexPath但是从不调用它们。这是我的代码:
class ChannelViewController: UIViewController, UISearchResultsUpdating, UICollectionViewDataSource, UICollectionViewDelegate {
var channelArray: [ChannelInfo] = []
var filteredSearchResults = [ChannelInfo]()
var resultsSearchController = UISearchController(searchResultsController: nil)
var logosShown = [Bool](count: 50, repeatedValue: false)
var detailUrl: String?
var apiKey = ""
var channel: String!
var channelForShow: String!
var task: NSURLSessionTask?
@IBOutlet var channelCollectionView: UICollectionView!
override func viewDidLoad() {
let baseURL = ""
getJSON(baseURL)
}
//MARK: CollectionView
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if resultsSearchController.active && resultsSearchController.searchBar.text != ""
{
return filteredSearchResults.count
} else {
return channelArray.count
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ChannelCell", forIndexPath: indexPath) as! ChannelCell
let channel: String
if resultsSearchController.active && resultsSearchController.searchBar.text != "" {
channel = self.filteredSearchResults[indexPath.row].logo
} else {
channel = self.channelArray[indexPath.row].logo
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var replacedTitle: String?
if resultsSearchController.active && resultsSearchController.searchBar.text != "" {
channelForShow = filteredSearchResults[indexPath.row].channelName
}
} else {
channelForShow = self.channelArray[indexPath.row].channelName
}
}
self.dismissSearchBar()
performSegueWithIdentifier("channelCollectToShowSegue", sender: self)
}
}
我还有一个用于collectionView Cell的子类:
class ChannelCell : UICollectionViewCell {
@IBOutlet var channelImageView: UIImageView!
}
答案 0 :(得分:1)
您需要将集合视图的数据源设置为控制器。
1)在“界面构建器”中,只需从集合视图拖动到控制器即可。并选择委托和数据源..
2)以编程方式
override func viewDidLoad() {
super.viewDidLoad()
channelCollectionView.delegate = self
channelCollectionView.dataSource = self
let baseURL = ""
getJSON(baseURL)
}
答案 1 :(得分:0)
想出来,忘记在故事板中连接委托和数据源。
答案 2 :(得分:0)
您是否设置了collectionView的委托和dataSource属性?如果没有,请将viewDidLoad更改为此,以便以编程方式设置这两个属性:
override func viewDidLoad() {
channelCollectionView.delegate = self
channelCollectionView.dataSource = self
let baseURL = ""
getJSON(baseURL)
}
如果没有设置delegate和dataSource,则collectionView将不知道在哪里调用适当的方法,例如cellForItemAtIndexPath。希望这可以解决您的问题。