質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1830閲覧

「Swift4.2」collectionViewにて、 TableViewでの、indexPathForSelectedRowに対応する記述を知りたい

tyaritta

総合スコア12

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2018/12/25 16:42

編集2018/12/27 19:31

前提・実現したいこと

collectionView内で、別のViewControllerで設定された値に更新したい。

質問の内容

collectionViewにて、
TableViewでの、indexPathForSelectedRowに対応する記述を知りたいです。
Swift4.2初心者です。
現在、
TableViewとテキスト入力用TableViewを連携している教材を元に、
collectionViewとテキスト入力用TableViewを連携しようとしておりました。
collectionView、テキスト入力用TableViewの記述が完了したため、
この二つを連携しようとしたところ、エラーメッセージが出てしまい、
半日ほど検索、試してみたのですが、どの方法をとってもうまく行きませんでした。
経験者の皆様の知恵をお借りしたいです。

発生している問題・エラーメッセージ

func inputViewControllerDone(_ controller:InputViewController) { if let indexPath = self.collectionView.indexPathsForSelectedItems{ ・・・}}

と打った際にエラーが表示されます。
元にした記述は下記です。

func inputViewControllerDone(_ controller:InputViewController) { if let indexPath = self.tableView.indexPathForSelectedRow { ・・・ }}

こちらのtableViewをcollectionView、
indexPathForSelectedRow をindexPathsForSelectedItems
と置き換えることで対応しようとしたところ、下記のエラーが表示されました。
エラーメッセージ

Ambiguous reference to member 'collectionView(_:numberOfItemsInSection:)'

該当のソースコード

collectionViewファイルの内容を記述しております。InputViewController.swiftというテキスト入力用のファイルが別途存在いたします。文字数オーバーのため、補足でコメントします。「//*****エラー個所」に該当のエラーが存在します。

import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,InputViewControllerDelegate { fileprivate let CellIdentifier = "Cell" override func viewDidLoad() { super.viewDidLoad() if (self.sections == nil) { self.sections = [[[AnyHashable: Any]]]() for section in 0..<1 { var records = [[AnyHashable:Any]]() for row in 0..<9 { let title = "(row)" var record = ["title":title,"memo":"memo"] records.append(record)} self.sections.append(records)}} let collectionViewLayout = UICollectionViewFlowLayout( let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout:collectionViewLayout) self.view.addSubview(collectionView) collectionView.translatesAutoresizingMaskIntoConstraints = false self.view.addConstraint( NSLayoutConstraint(item:collectionView, attribute:.left,relatedBy:.equal, toItem:self.view, attribute:.left, multiplier:1, constant:0)) self.view.addConstraint( NSLayoutConstraint(item:collectionView, attribute:.right,relatedBy:.equal, toItem:self.view, attribute:.right, multiplier:1, constant:0)) self.view.addConstraint( NSLayoutConstraint(item:collectionView, attribute:.top,relatedBy:.equal, toItem:self.topLayoutGuide, attribute:.bottom, multiplier:1, constant:0)) self.view.addConstraint( NSLayoutConstraint(item:collectionView, attribute:.bottom,relatedBy:.equal, toItem:self.bottomLayoutGuide, attribute:.top, multiplier:1, constant:0)) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier:CellIdentifier) collectionViewLayout.itemSize = CGSize(width: 110, height: 200) collectionViewLayout.sectionInset = UIEdgeInsets(top: 40, left: 10, bottom: 20, right: 10) collectionViewLayout.minimumInteritemSpacing = 10 collectionViewLayout.minimumLineSpacing = 10 collectionView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSections(in collectionView: UICollectionView) -> Int { return self.sections.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.sections[section].count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! CollectionViewCell let hue = Float((indexPath as NSIndexPath).row % 24) / 24.0 let saturation = Float(3 - (indexPath as NSIndexPath).section) / 3.0 cell.colorBox.backgroundColor = UIColor(hue: CGFloat(hue) , saturation: CGFloat(saturation), brightness: 1, alpha: 1) cell.label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) let record = self.sections[indexPath.section][indexPath.row] cell.label.text = record["title"] as? String cell.detaillabel.text = record["memo"] as? String return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell { print("(cell.label.text)が選択された。") } var record = self.sections[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row] let viewController = InputViewController(style:.grouped) // InputViewControllerにデリゲートを設定し項目のタイトルとメモを渡す。 viewController.inputDelegate = self viewController.text = record["title"] as? String viewController.memo = record["memo"] as? String self.navigationController?.pushViewController(viewController, animated: true) } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell { print("(cell.label.text)が選択解除された。") } } fileprivate var sections:[[[AnyHashable: Any]]]! func inputViewControllerDone(_ controller:InputViewController) { if let indexPath = self.collectionView.indexPathsForSelectedItems{//*****エラー個所 self.sections![(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]["title"] = controller.text self.sections![(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]["memo"] = controller.memo self.reloadRows(at: [indexPath], with: .none) self.selectRow(at: indexPath, animated: false, scrollPosition: .none) } } } class CollectionViewCell : UICollectionViewCell { let colorBox = UIView(frame: CGRect(x: 10,y: 10,width: 20,height: 20)) let label = UILabel() let detaillabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.contentView.addSubview(self.colorBox) self.contentView.addSubview(self.label) self.contentView.addSubview(self.detaillabel) self.label.translatesAutoresizingMaskIntoConstraints = false self.contentView.addConstraint(NSLayoutConstraint(item:self.label, attribute:.left,relatedBy:.equal, toItem:self.contentView, attribute:.left, multiplier:1, constant:4)) self.contentView.addConstraint(NSLayoutConstraint(item:self.label, attribute:.right,relatedBy:.equal, toItem:self.contentView, attribute:.right, multiplier:1, constant:-4)) self.contentView.addConstraint(NSLayoutConstraint(item:self.label, attribute:.top,relatedBy:.equal, toItem:self.contentView, attribute:.top, multiplier:1, constant:self.colorBox.frame.maxY + 4)) self.contentView.addConstraint(NSLayoutConstraint(item:self.label, attribute:.bottom,relatedBy:.equal, toItem:self.contentView, attribute:.bottom, multiplier:1, constant:-4)) self.detaillabel.translatesAutoresizingMaskIntoConstraints = false self.contentView.addConstraint(NSLayoutConstraint(item:self.detaillabel, attribute:.left,relatedBy:.equal, toItem:self.contentView, attribute:.left, multiplier:1, constant:4)) self.contentView.addConstraint(NSLayoutConstraint(item:self.detaillabel, attribute:.right,relatedBy:.equal, toItem:self.contentView, attribute:.right, multiplier:1, constant:-4)) self.contentView.addConstraint(NSLayoutConstraint(item:self.detaillabel, attribute:.top,relatedBy:.equal, toItem:self.contentView, attribute:.top, multiplier:1, constant:self.label.frame.maxY + 2))self.contentView.addConstraint(NSLayoutConstraint(item:self.detaillabel, attribute:.bottom,relatedBy:.equal, toItem:self.contentView, attribute:.bottom, multiplier:1, constant:-4)) self.backgroundColor = UIColor.lightGray self.selectedBackgroundView = UIView() self.selectedBackgroundView!.backgroundColor = UIColor.blue } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var isHighlighted:Bool { didSet { self.label.textColor = self.isHighlighted ? UIColor.white : UIColor.black } } override var isSelected:Bool { didSet { self.label.textColor = self.isSelected ? UIColor.white : UIColor.black } } }

Swift4.2です。

試したこと

①collectionViewを記入し、その候補内から、選択、記載。本来であれば、collectionViewだけで良いと思うのですが・・・
イメージ説明
↑の中から選択しても、エラーになってしまいます。
[collectionview]単体で選ぶことはできないのでしょうか。

②func inputViewControllerDone(_ controller:InputViewController)の記述を変更
(_ controller:InputViewController)の後ろに、collectionView:UICollectionView,cellForItemAt indexPath: IndexPath を追加。
そもそもデリゲートしてきたものになるので、そのような記載は不可と書かれてしまいました。
以上、皆様のお力添えを頂けますと大変助かります。
何卒宜しくお願い申し上げます。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

fuzzball

2018/12/26 01:46

「Bool型、Int型のCollectionViewの選択肢」ってどういう意味なんでしょうか?質問文全体的に、独特の言い回しが多くて何を言いたいのかよく分からないです。
tyaritta

2018/12/26 03:48

わかりづらく申し訳ございません。 帰宅次第、再度推敲致します。 文の意図としましては、swiftでは、 文字を打っている途中に、いくつか候補が出るかと思います。 選択肢とは、そちらのことを指しております。 例えばcollectionViewなら、 Bool collectionView(...) Int. collectionView(...)といった、選択肢のことです。
tyaritta

2018/12/27 20:17

下記の回答にて、該当箇所のエラーは解決致しましたので、締めさせていただきます。ご協力頂き誠に有難うございました。
guest

回答1

0

ベストアンサー

Ambiguous reference to member 'collectionView(_:numberOfItemsInSection:)'

質問とソース全体を読み切れてはいませんが、メンバー変数にcollectionViewが存在しないのではないでしょうか?

投稿2018/12/26 00:25

takabosoft

総合スコア8356

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tyaritta

2018/12/26 03:41

ご回答ありがとうございます。 let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout:collectionViewLayout) と、定義しているのですが、この定義だと不十分なのでしょうか。
takabosoft

2018/12/26 07:26 編集

let collectionView はviewDidLoad()関数内で定義されており、関数内で定義された変数は他のメンバー関数からは見えません。今回の場合であれば、クラスのメンバー変数(=ストアドプロパティ)として保持する必要があるかと思われます。メンバー変数であればクラスの他のメンバー関数内ではその変数を共有できます。
tyaritta

2018/12/27 20:07 編集

返信遅れてしまい申し訳ございません。 ご回答頂きありがとうございます。 試しにcollectionViewの記載位置をviewDidLoad()関数外に変えましたら、 該当箇所ではエラーが出なくなりました!(関数inputViewControllerDoneの処理内でエラーが出てくるようになったので、エラー内容を把握するように致します。)
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問