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

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

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

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

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

Q&A

解決済

1回答

1109閲覧

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)の解決方法が分かりません。

NobleNote

総合スコア4

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

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

0グッド

0クリップ

投稿2020/09/01 13:57

編集2020/09/02 00:30

前提・実現したいこと

Swift初学者です。
ToDoリストにメモした内容を遷移させて、URLに追加して検索をできるようにしたいと考えています。
コンパイルはできるのですが、Webに移動するボタンを押すとクラッシュしてしまいます。
CellにButtonを配置してSegueで遷移させようとしています。
エラーは

WebVC.link = self.memosA[(self.tableView.indexPathForSelectedRow?.row)!]

の部分に出ています。
よろしくお願いします。

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

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

該当のソースコード

import UIKit class FirstTableViewController: UITableViewController { let userDefaults = UserDefaults.standard // let userDefaults = UserDefaults.standard var memosA = [String]() var memosB = [String]() @IBAction func unwindToMemoList(sender: UIStoryboardSegue){ guard let sourceVC = sender.source as? SecondViewController, let memoA = sourceVC.food, let memoB = sourceVC.day else{ return } if let selectedIndexPath = self.tableView.indexPathForSelectedRow { self.memosA[selectedIndexPath.row] = memoA self.memosB[selectedIndexPath.row] = memoB } else { self.memosA.append(memoA) self.memosB.append(memoB) } self.userDefaults.set(self.memosA, forKey: "memosA") self.userDefaults.set(self.memosB, forKey: "memosB") self.tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() if self.userDefaults.object(forKey: "memosA") != nil { self.memosA = self.userDefaults.stringArray(forKey: "memosA")! } else { self.memosA = ["MemoA"] } if self.userDefaults.object(forKey: "memosB") != nil { self.memosB = self.userDefaults.stringArray(forKey: "memosB")! } else { self.memosB = ["MemoB"] } // if userDefaults.object(forKey: "memos") != nil { // self.memos = self.userDefaults.stringArray(forKey: "memos")! // } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.memosA.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FirstTableViewCell", for: indexPath) // Configure the cell... cell.textLabel?.text = self.memosA[indexPath.row] cell.detailTextLabel?.text = self.memosB[indexPath.row] return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source self.memosA.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) // } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. guard let identifier = segue.identifier else { return } if identifier == "editMemo" { let SecondVC = segue.destination as! SecondViewController SecondVC.food = self.memosA[(self.tableView.indexPathForSelectedRow?.row)!] SecondVC.day = self.memosB[(self.tableView.indexPathForSelectedRow?.row)!] } else if identifier == "goWeb" { let WebVC = segue.destination as! WebViewController WebVC.link = self.memosA[(self.tableView.indexPathForSelectedRow?.row)!] } else { return } } }

試したこと

そもそも遷移できていないのかと思って、WebVC.link = "単語" などにすると遷移に成功してサイトが表示されます。

補足情報(FW/ツールのバージョンなど)

遷移先のコードです。

import UIKit import WebKit class WebViewController: UIViewController { var link: String? @IBOutlet weak var browserWebView: WKWebView! override func viewDidLoad() { super.viewDidLoad() // print(link!) let urlString = "https://dotinstall.com/(link!)" let encordingUrl: String = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let urlRequest = URLRequest(url: URL(string: encordingUrl)!) self.browserWebView.load(urlRequest) // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }

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

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

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

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

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

guest

回答1

0

ベストアンサー

CellにButtonを配置してSegueで遷移させようとしています。

文面通り、「Cell に Button を配置」し、また Button から直接 Segue を引っ張ってきたのであれば、

エラーは

WebVC.link = self.memosA[(self.tableView.indexPathForSelectedRow?.row)!]

の部分に出ています。

の部分におけるindexPathForSelectedRow では値を取得することができません(Cell が直接選択されたのではなく、あくまでもボタンが選択されたため)。

indexPathForSelectedRow は、Cell が直接選択されたときに値が代入されるようになっているため、今回のように Cell に Button を配置した時にはどの Cell がタップしたのかまで検知することはできません。

簡単に解決には、Button を配置せず、Cell から Segue を引っ張るようにするのが一番簡単ですし、ソースコードを改変することなく動かすことも可能です。

あるいは、ちょっと強引にやるのであれば、UIButton の親を辿っていって UITableViewCell を見つけ出し、そこから indexPath を取得してやることも可能です(が、万が一パーツの重ねかたが私と質問者さんの設定で異なっていたら、以下の方法は使えませんし、スマートな方法ではないと思います)。

Swift

1 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 2 guard let identifier = segue.identifier else { 3 return 4 } 5 6 if identifier == "goWeb" { 7 if let button = sender as? UIButton { 8 if let cell = button.superview?.superview as? UITableViewCell { 9 // UIButton -> UIView -> UITableViewCell 10 if let indexPath = tableView.indexPath(for: cell) { 11 let WebVC = segue.destination as! WebViewController 12 WebVC.link = self.memosA[indexPath.row] 13 } 14 } 15 } 16 } 17 }

投稿2020/09/02 05:34

編集2020/09/02 05:35
TsukubaDepot

総合スコア5086

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

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

NobleNote

2020/09/02 09:13

ありがとうございます。同じCell内にあれば、同じように扱えると考えていました。Buttonを設置しただけでは値は取得できないんですね…。非常に勉強になりました。ありがとうございました。 CellからSegueを引っ張って遷移するように変更したところ、サイトに移動することができるようになりました! 分かりやすく教えていただき、ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問