質問編集履歴

1

誤字

2019/03/01 18:05

投稿

lilybelly
lilybelly

スコア19

test CHANGED
File without changes
test CHANGED
@@ -22,15 +22,503 @@
22
22
 
23
23
  試してみたんですがうまくいきませんでした。
24
24
 
25
+ ```swift
26
+
27
+ func calcDate(day:Int ,hour:Int ,baseDate:String ) -> Date {
28
+
29
+ /////////////////該当箇所///////////////////
30
+
31
+ ///////////////////////////////////////////
32
+
33
+ let formatter = DateFormatter()
34
+
35
+ // formatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale
36
+
37
+      //変更部分
38
+
39
+ formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
40
+
41
+ //
42
+
43
+ formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
44
+
45
+
46
+
47
+ var components = DateComponents()
48
+
49
+
50
+
51
+ components.setValue(day,for: Calendar.Component.day)
52
+
53
+ components.setValue(hour,for: Calendar.Component.hour)
54
+
55
+
56
+
57
+ let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
58
+
59
+
60
+
61
+ var base:Date?
62
+
63
+
64
+
65
+ if let _:String = baseDate {
66
+
67
+ print(formatter.date(from: baseDate))
68
+
69
+ print(baseDate)
70
+
71
+ if formatter.date(from: baseDate) != nil {
72
+
73
+ base = formatter.date(from: baseDate)!
74
+
75
+ } else {
76
+
77
+ print("baseDateの日付変換に失敗したので本日を使用します")
78
+
79
+ base = Date()
80
+
81
+ }
82
+
83
+
84
+
85
+ } else {
86
+
87
+ base = Date()
88
+
89
+ }
90
+
91
+ /////////////////該当箇所///////////////////
92
+
93
+ ///////////////////////////////////////////
94
+
95
+ return calendar.date(byAdding: components, to: base!)!
96
+
97
+ }
98
+
99
+ }
100
+
101
+ ```
102
+
25
103
  ##全体コード
26
104
 
27
105
 
28
106
 
29
107
  ```swift
30
108
 
109
+
110
+
111
+ import UIKit
112
+
113
+ import CoreData
114
+
115
+
116
+
117
+ //データを保存する画面
118
+
119
+ class ViewController: UIViewController, UITextFieldDelegate,UITextViewDelegate {
120
+
121
+ //それぞれUI部品を定義
122
+
123
+ @IBOutlet var titleField: UITextField!
124
+
125
+ @IBOutlet var memoTextView: UITextView!
126
+
127
+ @IBOutlet var memoNumLabel: UILabel!
128
+
129
+ @IBOutlet var companyField: UITextField!
130
+
131
+ @IBOutlet var dateField: UITextField!
132
+
133
+
134
+
135
+ //coreData(エンティティがMemo)
136
+
137
+ var memo:Memo?
138
+
139
+
140
+
141
+ //UIDatePickerを定義するための変数
142
+
143
+ var datePicker: UIDatePicker = UIDatePicker()
144
+
145
+ //resultDateで1日前を日付計算
146
+
147
+ var resultDate:Date?
148
+
149
+ //MemoTableViewConrtollerから引き渡されたcontext
150
+
151
+ var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
152
+
153
+
154
+
155
+
156
+
157
+ /*
158
+
159
+ 画面が呼ばれる前
160
+
161
+ */
162
+
163
+ override func viewDidAppear(_ animated: Bool) {
164
+
165
+ super.viewWillAppear(animated)
166
+
167
+
168
+
169
+ }
170
+
171
+ //テキストフィールド以外のところをタップするとキーボードが閉じる
172
+
173
+ @IBAction func tapScreen(_ sender: Any) {
174
+
175
+ self.view.endEditing(true)
176
+
177
+ }
178
+
179
+
180
+
181
+ /*
182
+
183
+ 画面が呼ばれた時
184
+
185
+ */
186
+
187
+ override func viewDidLoad() {
188
+
189
+ super.viewDidLoad()
190
+
191
+ titleField.delegate = self
192
+
193
+ memoTextView.delegate = self
194
+
195
+ companyField.delegate = self
196
+
197
+ dateField.delegate = self
198
+
199
+
200
+
201
+ // メモがなければ新規作成
202
+
203
+ if let memo = self.memo{
204
+
205
+ //メモの値を表示。
206
+
207
+ editedMemo(memo)
208
+
209
+ }
210
+
211
+
212
+
213
+ // ピッカー設定
214
+
215
+ datePicker.datePickerMode = UIDatePicker.Mode.dateAndTime
216
+
217
+ datePicker.timeZone = NSTimeZone.local
218
+
219
+ datePicker.locale = Locale(identifier: "ja")
220
+
221
+ dateField.inputView = datePicker
222
+
223
+
224
+
225
+ // 決定バーの生成
226
+
227
+ let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35))
228
+
229
+ let spacelItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
230
+
231
+ let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(ViewController.doneBtn))
232
+
233
+ toolbar.setItems([spacelItem, doneItem], animated: true)
234
+
235
+
236
+
237
+ // インプットビュー設定(紐づいているUITextfieldへ代入)
238
+
239
+ dateField.inputView = datePicker
240
+
241
+ dateField.inputAccessoryView = toolbar
242
+
243
+ //キーボードを閉じる
244
+
245
+ view.endEditing(true)
246
+
247
+ }
248
+
249
+ /*
250
+
251
+ ピッカーのdoneボタン
252
+
253
+ */
254
+
255
+
256
+
257
+ // UIDatePickerのDoneを押したら発火
258
+
259
+ @objc func doneBtn() {
260
+
261
+ dateField.endEditing(true)
262
+
263
+
264
+
265
+ // 日付のフォーマット
266
+
267
+ let formatter = DateFormatter()
268
+
269
+ //"yyyy年MM月dd日"を"yyyy/MM/dd"したりして出力の仕方を好きに変更できる
270
+
271
+ formatter.dateFormat = "yyyy年MM月dd日H時"
272
+
273
+ //datePickerで指定した日付が表示される
274
+
275
+ dateField.text = "(formatter.string(from: datePicker.date))"
276
+
277
+ let pickerTime = "(formatter.string(from: datePicker.date))"
278
+
279
+
280
+
281
+ //前日,日本時間を設定
282
+
283
+ resultDate = calcDate(day: -1 ,hour: 9 ,baseDate: pickerTime)
284
+
285
+ print(resultDate)
286
+
287
+ }
288
+
289
+
290
+
291
+ //入力ごとに文字数をカウントする
292
+
293
+ func textViewDidChange(_ textView: UITextView) {
294
+
295
+ let str = memoTextView.text
296
+
297
+ let commentNum = memoTextView.text.count
298
+
299
+ //空白と改行を抽出して取り除く
300
+
301
+ let newStr = String(str!.unicodeScalars
302
+
303
+ .filter(CharacterSet.whitespacesAndNewlines.contains)
304
+
305
+ .map(Character.init))
306
+
307
+ let numLabel = newStr.count
308
+
309
+ memoNumLabel.text = String(commentNum - numLabel)
310
+
311
+
312
+
313
+ }
314
+
315
+
316
+
317
+ func editedMemo(_ memo:Memo){
318
+
319
+ //編集用に表示
320
+
321
+ titleField.text = memo.title
322
+
323
+ companyField.text = memo.company
324
+
325
+ memoTextView.text = memo.memoText
326
+
327
+ memoNumLabel.text = memo.memoNum
328
+
329
+ dateField.text = memo.memoDate
330
+
331
+
332
+
333
+ }
334
+
335
+
336
+
337
+ @IBAction func saveMemo(_ sender: Any) {
338
+
339
+ //alertの設定
340
+
341
+ let alert: UIAlertController = UIAlertController(title: "メモの登録", message: "この内容で保存しますか?", preferredStyle: UIAlertController.Style.alert)
342
+
343
+
344
+
345
+ // キャンセルボタン
346
+
347
+ let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertAction.Style.cancel, handler:{
348
+
349
+ // ボタンが押された時の処理を書く(クロージャ実装)
350
+
351
+ (action: UIAlertAction!) -> Void in
352
+
353
+ print("Cancel")
354
+
355
+ })
356
+
357
+
358
+
359
+
360
+
361
+ // OKボタン押下時のイベント
362
+
363
+ let okAction = UIAlertAction(title: "OK", style: .default) { (action) in
364
+
365
+
366
+
367
+ // 編集の場合は詳細画面から渡されたself.memoを変更、
368
+
369
+ // 新規の場合は新しいMemoオブジェクトを作り、現在の日時を入れる_
370
+
371
+ let memo: Memo = {
372
+
373
+ if let memo = self.memo {
374
+
375
+ return memo
376
+
377
+ } else {
378
+
379
+ let memo = Memo(context: self.context)
380
+
381
+ memo.createdAt = Date()
382
+
383
+ return memo
384
+
385
+ }
386
+
387
+ }()
388
+
389
+
390
+
391
+ memo.title = self.titleField.text
392
+
393
+ memo.company = self.companyField.text
394
+
395
+ memo.memoText = self.memoTextView.text
396
+
397
+ memo.memoNum = self.memoNumLabel.text
398
+
399
+ memo.memoDate = self.dateField.text
400
+
401
+ memo.alertDate = self.resultDate
402
+
403
+
404
+
405
+ // 上で作成したデータをデータベースに保存
406
+
407
+ (UIApplication.shared.delegate as! AppDelegate).saveContext()
408
+
409
+
410
+
411
+ self.dismiss(animated: true, completion: nil)
412
+
413
+
414
+
415
+ //入力値をクリアにする
416
+
417
+ self.clearData()
418
+
419
+ }
420
+
421
+
422
+
423
+ func didReceiveMemoryWarning() {
424
+
425
+ super.didReceiveMemoryWarning()
426
+
427
+ }
428
+
429
+
430
+
431
+ alert.dismiss(animated: true, completion: nil)
432
+
433
+
434
+
435
+ // ③ UIAlertControllerにActionを追加
436
+
437
+ alert.addAction(cancelAction)
438
+
439
+ alert.addAction(okAction)
440
+
441
+
442
+
443
+ // ④ Alertを表示
444
+
445
+ present(alert, animated: true, completion: nil)
446
+
447
+
448
+
449
+ }
450
+
451
+ // 入力値をクリア
452
+
453
+ func clearData() {
454
+
455
+ titleField.text = ""
456
+
457
+ companyField.text = ""
458
+
459
+ memoTextView.text = ""
460
+
461
+ memoNumLabel.text = "0"
462
+
463
+ dateField.text = ""
464
+
465
+ }
466
+
467
+
468
+
469
+ func textFieldShouldReturn(_ textField: UITextField) -> Bool {
470
+
471
+ //キーボードを隠す
472
+
473
+ textField.resignFirstResponder()
474
+
475
+ return true
476
+
477
+ }
478
+
479
+
480
+
481
+ func applicationWillTerminate(_ application: UIApplication) {
482
+
483
+ self.saveContext()
484
+
485
+ }
486
+
487
+ //データを保存
488
+
489
+ func saveContext () {
490
+
491
+
492
+
493
+ let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
494
+
495
+ if context.hasChanges {
496
+
497
+ do {
498
+
499
+ try context.save()
500
+
501
+ print(context)
502
+
503
+
504
+
505
+ } catch {
506
+
507
+ let nserror = error as NSError
508
+
509
+ fatalError("Unresolved error (nserror), (nserror.userInfo)")
510
+
511
+ }
512
+
513
+ }
514
+
515
+ }
516
+
517
+
518
+
31
- func calcDate(day:Int ,hour:Int ,baseDate:String ) -> Date {
519
+ func calcDate(day:Int ,hour:Int ,baseDate:String ) -> Date {
32
-
520
+
33
- /////////////////該当箇所///////////////////
521
+ /////////////////該当箇所///////////////////
34
522
 
35
523
  ///////////////////////////////////////////
36
524
 
@@ -38,25 +526,21 @@
38
526
 
39
527
  // formatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale
40
528
 
41
-      //変更部分
42
-
43
529
  formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
44
530
 
45
- //
46
-
47
531
  formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
48
532
 
49
-
533
+
50
534
 
51
535
  var components = DateComponents()
52
536
 
53
-
537
+
54
538
 
55
539
  components.setValue(day,for: Calendar.Component.day)
56
540
 
57
541
  components.setValue(hour,for: Calendar.Component.hour)
58
542
 
59
-
543
+
60
544
 
61
545
  let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
62
546
 
@@ -104,488 +588,4 @@
104
588
 
105
589
  ```
106
590
 
107
- ```swift
108
-
109
-
110
-
111
- import UIKit
112
-
113
- import CoreData
114
-
115
-
116
-
117
- //データを保存する画面
118
-
119
- class ViewController: UIViewController, UITextFieldDelegate,UITextViewDelegate {
120
-
121
- //それぞれUI部品を定義
122
-
123
- @IBOutlet var titleField: UITextField!
124
-
125
- @IBOutlet var memoTextView: UITextView!
126
-
127
- @IBOutlet var memoNumLabel: UILabel!
128
-
129
- @IBOutlet var companyField: UITextField!
130
-
131
- @IBOutlet var dateField: UITextField!
132
-
133
-
134
-
135
- //coreData(エンティティがMemo)
136
-
137
- var memo:Memo?
138
-
139
-
140
-
141
- //UIDatePickerを定義するための変数
142
-
143
- var datePicker: UIDatePicker = UIDatePicker()
144
-
145
- //resultDateで1日前を日付計算
146
-
147
- var resultDate:Date?
148
-
149
- //MemoTableViewConrtollerから引き渡されたcontext
150
-
151
- var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
152
-
153
-
154
-
155
-
156
-
157
- /*
158
-
159
- 画面が呼ばれる前
160
-
161
- */
162
-
163
- override func viewDidAppear(_ animated: Bool) {
164
-
165
- super.viewWillAppear(animated)
166
-
167
-
168
-
169
- }
170
-
171
- //テキストフィールド以外のところをタップするとキーボードが閉じる
172
-
173
- @IBAction func tapScreen(_ sender: Any) {
174
-
175
- self.view.endEditing(true)
176
-
177
- }
178
-
179
-
180
-
181
- /*
182
-
183
- 画面が呼ばれた時
184
-
185
- */
186
-
187
- override func viewDidLoad() {
188
-
189
- super.viewDidLoad()
190
-
191
- titleField.delegate = self
192
-
193
- memoTextView.delegate = self
194
-
195
- companyField.delegate = self
196
-
197
- dateField.delegate = self
198
-
199
-
200
-
201
- // メモがなければ新規作成
202
-
203
- if let memo = self.memo{
204
-
205
- //メモの値を表示。
206
-
207
- editedMemo(memo)
208
-
209
- }
210
-
211
-
212
-
213
- // ピッカー設定
214
-
215
- datePicker.datePickerMode = UIDatePicker.Mode.dateAndTime
216
-
217
- datePicker.timeZone = NSTimeZone.local
218
-
219
- datePicker.locale = Locale(identifier: "ja")
220
-
221
- dateField.inputView = datePicker
222
-
223
-
224
-
225
- // 決定バーの生成
226
-
227
- let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35))
228
-
229
- let spacelItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
230
-
231
- let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(ViewController.doneBtn))
232
-
233
- toolbar.setItems([spacelItem, doneItem], animated: true)
234
-
235
-
236
-
237
- // インプットビュー設定(紐づいているUITextfieldへ代入)
238
-
239
- dateField.inputView = datePicker
240
-
241
- dateField.inputAccessoryView = toolbar
242
-
243
- //キーボードを閉じる
244
-
245
- view.endEditing(true)
246
-
247
- }
248
-
249
- /*
250
-
251
- ピッカーのdoneボタン
252
-
253
- */
254
-
255
-
256
-
257
- // UIDatePickerのDoneを押したら発火
258
-
259
- @objc func doneBtn() {
260
-
261
- dateField.endEditing(true)
262
-
263
-
264
-
265
- // 日付のフォーマット
266
-
267
- let formatter = DateFormatter()
268
-
269
- //"yyyy年MM月dd日"を"yyyy/MM/dd"したりして出力の仕方を好きに変更できる
270
-
271
- formatter.dateFormat = "yyyy年MM月dd日H時"
272
-
273
- //datePickerで指定した日付が表示される
274
-
275
- dateField.text = "(formatter.string(from: datePicker.date))"
276
-
277
- let pickerTime = "(formatter.string(from: datePicker.date))"
278
-
279
-
280
-
281
- //前日,日本時間を設定
282
-
283
- resultDate = calcDate(day: -1 ,hour: 9 ,baseDate: pickerTime)
284
-
285
- print(resultDate)
286
-
287
- }
288
-
289
-
290
-
291
- //入力ごとに文字数をカウントする
292
-
293
- func textViewDidChange(_ textView: UITextView) {
294
-
295
- let str = memoTextView.text
296
-
297
- let commentNum = memoTextView.text.count
298
-
299
- //空白と改行を抽出して取り除く
300
-
301
- let newStr = String(str!.unicodeScalars
302
-
303
- .filter(CharacterSet.whitespacesAndNewlines.contains)
304
-
305
- .map(Character.init))
306
-
307
- let numLabel = newStr.count
308
-
309
- memoNumLabel.text = String(commentNum - numLabel)
310
-
311
-
312
-
313
- }
314
-
315
-
316
-
317
- func editedMemo(_ memo:Memo){
318
-
319
- //編集用に表示
320
-
321
- titleField.text = memo.title
322
-
323
- companyField.text = memo.company
324
-
325
- memoTextView.text = memo.memoText
326
-
327
- memoNumLabel.text = memo.memoNum
328
-
329
- dateField.text = memo.memoDate
330
-
331
-
332
-
333
- }
334
-
335
-
336
-
337
- @IBAction func saveMemo(_ sender: Any) {
338
-
339
- //alertの設定
340
-
341
- let alert: UIAlertController = UIAlertController(title: "メモの登録", message: "この内容で保存しますか?", preferredStyle: UIAlertController.Style.alert)
342
-
343
-
344
-
345
- // キャンセルボタン
346
-
347
- let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertAction.Style.cancel, handler:{
348
-
349
- // ボタンが押された時の処理を書く(クロージャ実装)
350
-
351
- (action: UIAlertAction!) -> Void in
352
-
353
- print("Cancel")
354
-
355
- })
356
-
357
-
358
-
359
-
360
-
361
- // OKボタン押下時のイベント
362
-
363
- let okAction = UIAlertAction(title: "OK", style: .default) { (action) in
364
-
365
-
366
-
367
- // 編集の場合は詳細画面から渡されたself.memoを変更、
368
-
369
- // 新規の場合は新しいMemoオブジェクトを作り、現在の日時を入れる_
370
-
371
- let memo: Memo = {
372
-
373
- if let memo = self.memo {
374
-
375
- return memo
376
-
377
- } else {
378
-
379
- let memo = Memo(context: self.context)
380
-
381
- memo.createdAt = Date()
382
-
383
- return memo
384
-
385
- }
386
-
387
- }()
388
-
389
-
390
-
391
- memo.title = self.titleField.text
392
-
393
- memo.company = self.companyField.text
394
-
395
- memo.memoText = self.memoTextView.text
396
-
397
- memo.memoNum = self.memoNumLabel.text
398
-
399
- memo.memoDate = self.dateField.text
400
-
401
- memo.alertDate = self.resultDate
402
-
403
-
404
-
405
- // 上で作成したデータをデータベースに保存
406
-
407
- (UIApplication.shared.delegate as! AppDelegate).saveContext()
408
-
409
-
410
-
411
- self.dismiss(animated: true, completion: nil)
412
-
413
-
414
-
415
- //入力値をクリアにする
416
-
417
- self.clearData()
418
-
419
- }
420
-
421
-
422
-
423
- func didReceiveMemoryWarning() {
424
-
425
- super.didReceiveMemoryWarning()
426
-
427
- }
428
-
429
-
430
-
431
- alert.dismiss(animated: true, completion: nil)
432
-
433
-
434
-
435
- // ③ UIAlertControllerにActionを追加
436
-
437
- alert.addAction(cancelAction)
438
-
439
- alert.addAction(okAction)
440
-
441
-
442
-
443
- // ④ Alertを表示
444
-
445
- present(alert, animated: true, completion: nil)
446
-
447
-
448
-
449
- }
450
-
451
- // 入力値をクリア
452
-
453
- func clearData() {
454
-
455
- titleField.text = ""
456
-
457
- companyField.text = ""
458
-
459
- memoTextView.text = ""
460
-
461
- memoNumLabel.text = "0"
462
-
463
- dateField.text = ""
464
-
465
- }
466
-
467
-
468
-
469
- func textFieldShouldReturn(_ textField: UITextField) -> Bool {
470
-
471
- //キーボードを隠す
472
-
473
- textField.resignFirstResponder()
474
-
475
- return true
476
-
477
- }
478
-
479
-
480
-
481
- func applicationWillTerminate(_ application: UIApplication) {
482
-
483
- self.saveContext()
484
-
485
- }
486
-
487
- //データを保存
488
-
489
- func saveContext () {
490
-
491
-
492
-
493
- let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
494
-
495
- if context.hasChanges {
496
-
497
- do {
498
-
499
- try context.save()
500
-
501
- print(context)
502
-
503
-
504
-
505
- } catch {
506
-
507
- let nserror = error as NSError
508
-
509
- fatalError("Unresolved error (nserror), (nserror.userInfo)")
510
-
511
- }
512
-
513
- }
514
-
515
- }
516
-
517
-
518
-
519
- func calcDate(day:Int ,hour:Int ,baseDate:String ) -> Date {
520
-
521
- /////////////////該当箇所///////////////////
522
-
523
- ///////////////////////////////////////////
524
-
525
- let formatter = DateFormatter()
526
-
527
- // formatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale
528
-
529
- formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
530
-
531
- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
532
-
533
-
534
-
535
- var components = DateComponents()
536
-
537
-
538
-
539
- components.setValue(day,for: Calendar.Component.day)
540
-
541
- components.setValue(hour,for: Calendar.Component.hour)
542
-
543
-
544
-
545
- let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
546
-
547
-
548
-
549
- var base:Date?
550
-
551
-
552
-
553
- if let _:String = baseDate {
554
-
555
- print(formatter.date(from: baseDate))
556
-
557
- print(baseDate)
558
-
559
- if formatter.date(from: baseDate) != nil {
560
-
561
- base = formatter.date(from: baseDate)!
562
-
563
- } else {
564
-
565
- print("baseDateの日付変換に失敗したので本日を使用します")
566
-
567
- base = Date()
568
-
569
- }
570
-
571
-
572
-
573
- } else {
574
-
575
- base = Date()
576
-
577
- }
578
-
579
- /////////////////該当箇所///////////////////
580
-
581
- ///////////////////////////////////////////
582
-
583
- return calendar.date(byAdding: components, to: base!)!
584
-
585
- }
586
-
587
- }
588
-
589
- ```
590
-
591
591
  アドバイスいただきたいです。よろしくお願いします。