Just starting my journey in Swift and was following a vague YouTube tutorial. I'm having an issue calling the ContentView from the Main App. Any help is greatly appreciated along with any recommended material for learning the Swift language.
(I come from a Salesforce Developer background so I'm semi fluent in Java, HTML, SOQL, and Javascript)
Main App:
import SwiftUI
@main
struct RoundBarrelSocietyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
ContentView:
import SwiftUI
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", for: .normal)
button.setTitleColor(.black, for: .normal)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBlue
view.addSubview(imageView)
imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
imageView.center = view.center
getRandomPhoto()
button.addTarget(self, action: #selector(didTapButton),
for: .touchUpInside)
}
@objc func didTapButton() {
getRandomPhoto()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view.addSubview(button)
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)
}
}