-
Notifications
You must be signed in to change notification settings - Fork 0
/
ViewController.swift
75 lines (62 loc) · 1.91 KB
/
ViewController.swift
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
//
// ViewController.swift
// RandomPhotoGenerator
//
// Created by Lindelani on 30/05/2022.
//
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("Generate Random Photo", for: .normal)
button.setTitleColor(.black, for: .normal)
return button
}()
let colors: [UIColor] = [
.systemPink,
.systemIndigo,
.systemGray,
.systemBlue,
.systemCyan,
.systemMint,
.systemOrange
]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemPink
view.addSubview(imageView)
imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
imageView.center = view.center
view.addSubview(button)
getRandomPhoto()
button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
}
@objc func didTapButton() {
getRandomPhoto()
view.backgroundColor = colors.randomElement()
}
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)
}
func getRandomPhoto() {
let urlString =
"https://source.unsplash.com/random/600x600"
let url = URL(string: urlString)!
guard let data = try? Data(contentsOf: url) else {
return
}
imageView.image = UIImage(data: data)
}
}