質問するログイン新規登録

質問編集履歴

1

前回、実現できたコードを入力しました。

2019/02/13 03:22

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  class ViewController: UIViewController {
7
7
 
8
- @IBOutlet weak var createUILabel: UIButton! // UILbelランダムで出力するボタン
8
+ @IBOutlet weak var createUILabel: UIButton! // UILabelを出力するボタン
9
9
  @IBOutlet weak var loadButton: UIButton! //ロードボタン
10
10
  @IBOutlet weak var saveButton: UIButton! //セーブボタン
11
11
 
@@ -23,7 +23,7 @@
23
23
 
24
24
  }
25
25
 
26
- //UILabelをランダムの位置に表示する処理
26
+ //UILabelを出力する処理
27
27
  @IBAction func actionCreateUIButton(_ sender: UIButton) {
28
28
 
29
29
  let randX = Int(arc4random_uniform(300))
@@ -53,4 +53,72 @@
53
53
 
54
54
  }
55
55
 
56
+ ```
57
+
58
+
59
+ UIlabelを保存というのは良くない表現でした。UIlabelのプロパティを保存するという意味でした。失礼しました。
60
+ 以下、UILabelをuserDefaultsに保存することは実現できたコードです。
61
+
62
+ ```swift
63
+
64
+ import UIKit
65
+
66
+ class ViewController: UIViewController {
67
+
68
+ @IBOutlet weak var createButton: UIButton! //UILabelを出力するボタン
69
+ @IBOutlet weak var loadButton: UIButton! //ロードボタン
70
+ @IBOutlet weak var saveButton: UIButton! //セーブボタン
71
+
72
+ let save = UserDefaults.standard
73
+
74
+ let testLabel = UILabel()
75
+
76
+ override func viewDidLoad() {
77
+
78
+ super.viewDidLoad()
79
+
80
+ createButton.backgroundColor = UIColor.darkGray
81
+ loadButton.backgroundColor = UIColor.blue
82
+ saveButton.backgroundColor = UIColor.red
83
+
84
+ }
85
+
86
+ //UILabelを表示する処理
87
+ @IBAction func actionCreateButton(_ sender: UIButton) {
88
+
89
+ let randX = Int(arc4random_uniform(300))
90
+ let randY = Int(arc4random_uniform(300))
91
+
92
+ testLabel.text = String("テスト")
93
+ testLabel.sizeToFit()
94
+ testLabel.center = CGPoint(x: randX, y: randY)
95
+
96
+ view.addSubview(testLabel)
97
+ print(testLabel.frame.origin.x)
98
+ print(testLabel.frame.origin.y)
99
+
100
+ }
101
+
102
+ //UILabelのプロパティを保存する処理
103
+ @IBAction func actionSaveButton(_ sender: UIButton) {
104
+
105
+ save.set(testLabel.center.x, forKey: "hoge")
106
+ save.set(testLabel.center.y, forKey: "fuga")
107
+ save.set(testLabel.text, forKey: "piyo")
108
+ save.synchronize()
109
+
110
+ }
111
+
112
+ //UIlabelのプロパティを出力する処理
113
+ @IBAction func actionLoadButton(_ sender: UIButton) {
114
+
115
+ testLabel.center = CGPoint(x: save.integer(forKey: "hoge"), y: save.integer(forKey: "fuga"))
116
+ testLabel.text = save.object(forKey: "piyo") as? String
117
+ testLabel.sizeToFit()
118
+ view.addSubview(testLabel)
119
+
120
+ }
121
+ }
122
+
123
+
56
124
  ```