У меня есть UITableViewController, внутри TableViewCell это UICollectionView. Я хочу передать данные из CollectionViewCell в DetailViewController, когда пользователь постучал по ячейке. Я перетащил segue из CollectionViewCell в DetailViewController и использовал «didSelectItemAtIndexPath» внутри TableViewCell (который содержит CollectionView), и он работает.Swift: Как использовать «didSelectItemAtIndexPath» в UITableViewController (содержит UICollectionView)?
class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
var posts1: [Posts] = [Posts]()
var posts2: [Posts] = [Posts]()
var categories: [Category] = [Category]()
var selectedPost1: Posts?
@IBOutlet weak var theCollectionView: UICollectionView!
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return posts1.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let collectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
let imageUrlString: String = posts1[indexPath.row].postThumbnailUrlString
let imageUrl: NSURL = NSURL(string: imageUrlString)!
//Give Images A round cornor
let filter = AspectScaledToFillSizeWithRoundedCornersFilter(
size: collectionViewCell.postImageView.frame.size,
radius: 20.0
)
collectionViewCell.postImageView.af_setImageWithURL(imageUrl, filter: filter)
collectionViewCell.postTitleLabel.text = posts1[indexPath.row].postTite
return collectionViewCell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("selected")
self.selectedPost1 = self.posts1[indexPath.row]
}
он может напечатать «выбранный», что означает, что данные уже сохранены в «self.selectedPost1». Но я не могу использовать «prepareForSegue» внутри этого класса, так как он может использоваться только в ViewController. кто-то сказал мне, чтобы реализовать «UICollectionViewDelegate» в моем «HomeTableViewController», и вызовите функцию «didSelectedItemAtIndexPath» в HomeTableViewController, как это:
import UIKit
class HomePageTableViewController: UITableViewController,UICollectionViewDelegate {
let sections: NSArray = ["latest news", "good news"]
var posts1: [Posts] = [Posts]()
var selectedIndexPath: NSIndexPath?
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < sections.count{
return sections[section] as? String
}
return nil
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 && indexPath.section == 0 {
let tableViewCell = tableView.dequeueReusableCellWithIdentifier("TableViewCell") as! TableViewCell
tableViewCell.getCategories()
// tableViewCell.scrollToNextCell()
// tableViewCell.startTimer()
return tableViewCell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("goToDetail", sender: TableViewCell())
print("selected")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let tableViewCell1 = sender as? TableViewCell,
let postDetailPage = segue.destinationViewController as? DetailViewController{
let selectedPosts = tableViewCell1.selectedPost1
postDetailPage.selectedPost?.selectedPost1 = selectedPosts
}
Однако «didSelectedItemAtIndexPath» нельзя назвать, нет Распечатать. Я не знаю почему?
вот мой DetailViewController:
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var postImageView: UIImageView!
var posts: [Posts] = [Posts]()
var selectedPost: TableViewCell?
override func viewDidLoad() {
super.viewDidLoad()
if let post = selectedPost?.selectedPost1{
let thumbnailUrlString = post.postThumbnailUrlString
let imageUrl: NSURL = NSURL(string: thumbnailUrlString)!
print(thumbnailUrlString)
postImageView.af_setImageWithURL(imageUrl)
}
}
, а также мне нужно реализовать в viewDidLoad или viewDidAppear?
В течение нескольких дней я боролся с этой проблемой? нужны некоторые предложения о том, как сделать Segue из UICollectionViewCell (который находится внутри UITableViewCell) новому UIViewController. большое спасибо.
для CollectionView внутри didSelectRowAtIndexPath, удалите SEGUE и обновить меня, если он напечатает «выбран» – jo3birdtalk
я удалил Segue, и он все еще может печатать «выбран» после того, как я постучал по сотовому –
I предложите обратиться [этот код github] (https://github.com/DipenPanchasara/UITableViewWithHorizontalScroll), который имеет ту же самую реализацию, которая вам нужна. Хотя в вашем коде вам нужно установить делегат 'UICollectionView' внутри' cellForRowAtIndexPath', используя 'cell.objectOfCollectionview'. –