-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViewController.swift
More file actions
82 lines (67 loc) · 2.52 KB
/
ViewController.swift
File metadata and controls
82 lines (67 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import UIKit
class ViewController: UIViewController {
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.backgroundColor = .white
return imageView
}()
private let button : UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.setTitle("Random Photo Generator", for: .normal)
button.setTitleColor(.black, for: .normal)
return button
}()
private let label: UILabel = {
let label = UILabel()
label.textColor = .black
label.textAlignment = .center
label.text = "Created by Leon Tang"
label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .systemPink
view.addSubview(imageView)
imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
imageView.center = view.center
view.addSubview(button)
button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
getRandomPhoto()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
button.frame = CGRect(x: 30,
y: view.frame.size.height - 150 - view.safeAreaInsets.bottom,
width: view.frame.size.width - 60,
height: 55
)
label.frame = CGRect(x: 20,
y: view.frame.size.height - 80 - view.safeAreaInsets.bottom,
width: view.frame.size.width - 40,
height: 20)
}
@objc func didTapButton() {
getRandomPhoto()
}
func getRandomPhoto() {
let urlString = "https://picsum.photos/200/300"
guard let url = URL(string: urlString) else {
return
}
URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
guard let self = self,
error == nil,
let data = data,
let image = UIImage(data: data) else {
return
}
DispatchQueue.main.async {
self.imageView.image = image
}
}.resume()
}
}