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

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

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

TableView(UITableView)とは、リスト形式で表示するコントロールで、ほとんどのアプリに使用されています。画面を「行」に分けて管理し、一般的には各行をタップした際に詳細画面に移動します。

iOS

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

Xcode

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

Swift

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

iPhone

iPhoneとは、アップル社が開発・販売しているスマートフォンです。 同社のデジタルオーディオプレーヤーiPodの機能、電話機能、インターネットやメールなどのWeb通信機能の3つをドッキングした機器です。

Q&A

解決済

3回答

242閲覧

関数の引数・返り値などについて

退会済みユーザー

退会済みユーザー

総合スコア0

TableView

TableView(UITableView)とは、リスト形式で表示するコントロールで、ほとんどのアプリに使用されています。画面を「行」に分けて管理し、一般的には各行をタップした際に詳細画面に移動します。

iOS

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

Xcode

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

Swift

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

iPhone

iPhoneとは、アップル社が開発・販売しているスマートフォンです。 同社のデジタルオーディオプレーヤーiPodの機能、電話機能、インターネットやメールなどのWeb通信機能の3つをドッキングした機器です。

0グッド

0クリップ

投稿2018/04/29 07:30

編集2018/05/01 06:29

swift

1import UIKit 2 3class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{ 4 5 @IBOutlet weak var mytableView: UITableView! 6 var item = [String]() 7 8 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 9 return item.count 10 } 11 12 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 13 let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 14 let todoLabel = item[indexPath.row] 15 cell.textLabel?.text = todoLabel 16 17 //ボタンについて 18 let button = UIButton() 19 button.backgroundColor = UIColor.blue 20 button.setTitle(" 追 加 ", for: .normal) 21 cell.contentView.addSubview(button) 22 23 button.translatesAutoresizingMaskIntoConstraints = false 24 cell.contentView.rightAnchor.constraint(equalTo: button.rightAnchor, constant: 12).isActive = true 25 // 中央にする 26 //button.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true 27 //丸みに対して 28 button.layer.cornerRadius = 10 29 button.layer.masksToBounds = true 30 31 cell.contentView.heightAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true 32 33 //ラベルについて 34 var label = UILabel() 35 label.backgroundColor = UIColor.darkGray 36 label.text = "120×10" 37 //丸みに対して 38 label.layer.cornerRadius = 5 39 label.layer.masksToBounds = true 40 cell.contentView.addSubview(label) 41 42 label.translatesAutoresizingMaskIntoConstraints = false 43 cell.contentView.leftAnchor.constraint(equalTo: label.leftAnchor, constant: -6).isActive = true 44 cell.contentView.heightAnchor.constraint(equalTo: label.heightAnchor, multiplier: 1).isActive = true 45 46 //アラート 47 func addalert()-> String{ 48 let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert) 49 50 // OKボタンの設定 51 let okAction = UIAlertAction(title: "OK", style: .default, handler: { 52 (action:UIAlertAction!) -> Void in 53 54 // OKを押した時入力されていたテキストを表示 55 if let textFields = alert.textFields { 56 57 // アラートに含まれるすべてのテキストフィールドを調べる 58 for textField in textFields { 59 60 self.item.insert(textField.text!, at: 0) 61 self.label.text = textField.text! 62 self.mytableView.insertRows(at: [IndexPath(row: 0, section: 0)],with: UITableViewRowAnimation.automatic) 63 print(textField.text!) 64 } 65 } 66 }) 67 alert.addAction(okAction) 68 69 // キャンセルボタンの設定 70 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) 71 alert.addAction(cancelAction) 72 73 // テキストフィールドを追加 74 alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in 75 textField.placeholder = "テキスト" 76 }) 77 78 alert.view.setNeedsLayout() // シミュレータの種類によっては、これがないと警告が発生 79 80 // アラートを画面に表示 81 self.present(alert, animated: true, completion: nil) 82 } 83 return cell 84 } 85 86@IBAction func addlabel(_ sender: Any) { 87 88 let key = addalert()//alertの値を渡したつもり 89 90 } 91 92 93 override func viewDidLoad() { 94 super.viewDidLoad() 95 96 } 97 98 99 100 override func didReceiveMemoryWarning() { 101 super.didReceiveMemoryWarning() 102 // Dispose of any resources that can be recreated. 103 } 104 105 106}

やりたいこと

ボタンをタップした時、アラートを呼び出したい。

困っていること
cellForRowAtの中にアラートを書いてしまった為にアラートを呼び出せなくなってしまった。

試したこと
func addalert()-> String{を関数として@IBAction func addlabel(_ sender: Any) {に値を渡そうとしているが大学のC言語で勉強した程度しか関数への理解が乏しいのでエラーが取れずに困っています

** エラーメッセージ**
Use of unresolved identifier 'addalert'

イメージ説明
イメージ説明

イメージ

swift

1//labelインスタンス 2 //label1 3 let label = UILabel() 4 label.backgroundColor = UIColor.darkGray 5 //label2 6 let label2 = UILabel() 7 label2.backgroundColor = UIColor.darkGray 8 //label3 9 let label3 = UILabel() 10 label3.backgroundColor = UIColor.darkGray 11 //label4 12 let label4 = UILabel() 13 label4.backgroundColor = UIColor.darkGray 14 //label5 15 let label5 = UILabel() 16 label5.backgroundColor = UIColor.darkGray 17

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

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

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

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

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

退会済みユーザー

退会済みユーザー

2018/04/29 12:17

エラーメッセージくらい載せよう
退会済みユーザー

退会済みユーザー

2018/04/29 13:21

すいません、追記しました。
guest

回答3

0

ベストアンサー

itemに入力した値を格納しているので戻り値で設定せずにitemに格納した値を設定してあげれば良いのではないでしょうか?

import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{ @IBOutlet weak var mytableView: UITableView! var item = [String]() func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return item.count } //アラート func addalert() { ... // OKボタンの設定 let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action:UIAlertAction!) -> Void in // OKを押した時入力されていたテキストを表示 if let textFields = alert.textFields { // アラートに含まれるすべてのテキストフィールドを調べる for textField in textFields { self.item.insert(textField.text!, at: 0) self.mytableView.insertRows(at: [IndexPath(row: 0, section: 0)],with: UITableViewRowAnimation.automatic) print(textField.text!) } } }) ... } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { ... //ラベルについて let label = UILabel() label.backgroundColor = UIColor.darkGray // itemに格納した値を設定 if indexPath.row < item.count { label.text = item[indexPath.row] } ... } @IBAction func addlabel(_ sender: Any) { addalert() } ... }

[追記]

import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{ @IBOutlet weak var mytableView: UITableView! var item = [String]() func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return item.count } //アラート func addalert() { let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert) // OKボタンの設定 let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action:UIAlertAction!) -> Void in // OKを押した時入力されていたテキストを表示 if let textFields = alert.textFields { // アラートに含まれるすべてのテキストフィールドを調べる for textField in textFields { self.item.insert(textField.text!, at: 0) self.mytableView.insertRows(at: [IndexPath(row: 0, section: 0)],with: UITableViewRowAnimation.automatic) print(textField.text!) } } }) alert.addAction(okAction) // キャンセルボタンの設定 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(cancelAction) // テキストフィールドを追加 alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in textField.placeholder = "テキスト" }) alert.view.setNeedsLayout() // シミュレータの種類によっては、これがないと警告が発生 // アラートを画面に表示 self.present(alert, animated: true, completion: nil) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let todoLabel = item[indexPath.row] cell.textLabel?.text = todoLabel //ボタンについて let button = UIButton() button.backgroundColor = UIColor.blue button.setTitle(" 追 加 ", for: .normal) cell.contentView.addSubview(button) button.translatesAutoresizingMaskIntoConstraints = false cell.contentView.rightAnchor.constraint(equalTo: button.rightAnchor, constant: 12).isActive = true // 中央にする //button.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true //丸みに対して button.layer.cornerRadius = 10 button.layer.masksToBounds = true cell.contentView.heightAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true //ラベルについて let label = UILabel() label.backgroundColor = UIColor.darkGray if indexPath.row < item.count { label.text = item[indexPath.row] } //丸みに対して label.layer.cornerRadius = 5 label.layer.masksToBounds = true cell.contentView.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false cell.contentView.leftAnchor.constraint(equalTo: label.leftAnchor, constant: -6).isActive = true cell.contentView.heightAnchor.constraint(equalTo: label.heightAnchor, multiplier: 1).isActive = true return cell } @IBAction func addlabel(_ sender: Any) { addalert() } override func viewDidLoad() { super.viewDidLoad() mytableView.dataSource = self mytableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } }

投稿2018/04/29 21:21

編集2018/04/30 00:06
newmt

総合スコア1277

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

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

退会済みユーザー

退会済みユーザー

2018/04/29 23:30

@newmtさん が提示して頂いた上記のコードですと、cellForRowAt内のlabelのインスタンスが呼び出せなくなるのでそうするとlabelをcellに挿入出来なくなってしまいます。なのでcellForRowAt内のalertをなんとか呼び出せないかをもしお分かりでしたら教えて頂けたら嬉しいです。
newmt

2018/04/29 23:35

私がやりたいことを勘違いしているのかもしれませんが、アラートのOKボタンの処理の中で self.mytableView.insertRows とされているのでアラートで入力するごとに新しい行を追加するというものではないのでしょうか?
退会済みユーザー

退会済みユーザー

2018/04/29 23:50

すいませんでした。提示して頂いたコードを勘違いしていました。 なのでやりたい事としては出来ました。しかし、labelが挿入されると同時にitemのテキストも挿入されているので見た目的におかしな状態になっています。コードを見てみてもlabelとitemは紐ずけられているのでセルの中に入るのはlabelだけになると思うのですがなぜitemのテキストも挿入されるのでしょうか?
newmt

2018/04/30 00:07

私の環境ですと起きませんが、追記したコードで実行しても起きますでしょうか?
退会済みユーザー

退会済みユーザー

2018/04/30 00:36

let todoLabel = item[indexPath.row] cell.textLabel?.text = todoLabel 解決できました。 調べてみましたら上記の部分のせいで二重に挿入されていました。 それとなんですが5回まで同列内のセルに左詰でlabelを挿入させていきたいのですがその場合5つlabelのインスタンスを用意しなければならないんでしょうか? 私としてはfor文を使うと一個のインスタンスで出来るのではないかと思うのですが出来ますでしょうか?
newmt

2018/05/01 06:17

>5つlabelのインスタンスを用意しなければならないんでしょうか? インスタンスが同じですと結局そのインスタンスの値を上書きしているだけになるので、1個のインスタンスではできないと思います。
退会済みユーザー

退会済みユーザー

2018/05/01 06:35

質問にコードを追記しました。このように五つlabelを用意した後、var itemも五つ用意し、解答して頂いたようにif文で条件分岐をすれば私のイメージすることが出来るのでしょうか? alertについてもいじる必要があるのでしょうか?
guest

0

cellForRowAtの中にアラートを書いてしまった為にアラートを呼び出せなくなってしまった。

cellForRowAtの外にアラートを書けば良いのでは?

swift

1@IBAction func addlabel(_ sender: Any) { 2 3 let key = addalert()//alertの値を渡したつもり 4 5} 6 7//アラート 8func addalert()-> String{ 9 ... 10}

投稿2018/04/29 14:48

koogawa

総合スコア494

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

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

退会済みユーザー

退会済みユーザー

2018/04/29 17:27

外に書くとエラーは取れるのですがその場合だとアラートで追加したいものを追加出来なくなるので今回は関数を利用してなんとか結びつけたいと考えています
guest

0

エラーメッセージでググろう

投稿2018/04/29 13:22

退会済みユーザー

退会済みユーザー

総合スコア0

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

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

退会済みユーザー

退会済みユーザー

2018/04/29 17:25

宣言していない変数等を記入しているために出るエラーっていうのは分かるのですがどうすればいいか分からないので質問させて頂きました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問