Adding textfeilds on top of drawing veiw image XCode SwiftUI - ios

Essentially I would like to add text fields on top of my image.
Currently, my viewDidLoad() is currently set up as such.
-Image Background (UIImage)
--Drawing Canvas
I would like it to be set up as such so that it is not possible to draw over the text fields, as I realize it is possible to add text over the image itself
-Image Background (UIImage)
---Drawing Canvas
-----TextFeild Struct
I would assume I need to use UITextField but I keep on getting this error in my simulation.
(Fatal error: Unexpectedly found nil while implicitly unwrapping an
Optional value)
In addition to this error, I'm unable to edit the scaling of my image background. I tried everything turning the imageView to content mode, and modifying the image before adding the view (scaleAspectFit/scaleAspectFill), resizing the view the only thing that seemed to work was changing the resolution of the source image.
I would like to add text fields up top right
class DrawingCanvasViewController: UIViewController {
#IBOutlet weak var nameTextField: UITextField!
lazy var canvas: PKCanvasView = {
let view = PKCanvasView()
view.drawingPolicy = .anyInput
view.minimumZoomScale = 1
view.maximumZoomScale = 1
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var toolPicker: PKToolPicker = {
let toolPicker = PKToolPicker()
toolPicker.addObserver(self)
return toolPicker
}()
var drawingData = Data()
var drawingChanged: (Data) -> Void = {_ in}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(canvas)
canvas.backgroundColor = .clear
let iTest=UIImage(named: "Test2")
let imageView=UIImageView(image: iTest)
//This is what I have used for trying to resize my background image, although none of it seems to ever work
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
//The fatal error it gives me is from these two lines below
// view.addSubview(nameTextField)
// view.bringSubviewToFront(nameTextField)
NSLayoutConstraint.activate([
canvas.leadingAnchor.constraint(equalTo: view.leadingAnchor),
canvas.trailingAnchor.constraint(equalTo: view.trailingAnchor),
canvas.topAnchor.constraint(equalTo: view.topAnchor),
canvas.bottomAnchor.constraint(equalTo: view.bottomAnchor)])
toolPicker.setVisible(true, forFirstResponder: canvas)
toolPicker.addObserver(canvas)
canvas.delegate = self
canvas.becomeFirstResponder()
if let drawing = try? PKDrawing(data: drawingData){
canvas.drawing = drawing
}
}
}
I'm new to Xcode, I did follow a tutorial to add the pencil kit UI although am currently unable to refind it, and I figured out how to add the background image from looking at apple documentation, Hence I may have simply missed an easier/better way to code my app.

what I'm seeing from your code is: that you added UITextField in your Xib/Storyboard file. Therefore you can remove the reference of UITextField in the Xib/Storyboard file with the controller and introduce UITextField programmatically. My solution below will only address the fatal error from the 2 lines:
view.addSubview(nameTextField)
view.bringSubviewToFront(nameTextField)
Then let me know other issues when you get this one working first. Please adjust the contrainst of nameTextField to have it visible.
class DrawingCanvasViewController: UIViewController {
// initialise text field
lazy var nameTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
// Please setup delegate by yourself
return textField
}()
lazy var canvas: PKCanvasView = {
let view = PKCanvasView()
view.drawingPolicy = .anyInput
view.minimumZoomScale = 1
view.maximumZoomScale = 1
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var toolPicker: PKToolPicker = {
let toolPicker = PKToolPicker()
toolPicker.addObserver(self)
return toolPicker
}()
var drawingData = Data()
var drawingChanged: (Data) -> Void = {_ in}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(canvas)
canvas.backgroundColor = .clear
let iTest=UIImage(named: "Test2")
let imageView=UIImageView(image: iTest)
//This is what I have used for trying to resize my background image,
// although none of it seems to ever work
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
// since you already created the nameTextField as a lazy variable
// then you can add it here
view.addSubview(nameTextField)
view.bringSubviewToFront(nameTextField)
NSLayoutConstraint.activate([
canvas.leadingAnchor.constraint(equalTo: view.leadingAnchor),
canvas.trailingAnchor.constraint(equalTo: view.trailingAnchor),
canvas.topAnchor.constraint(equalTo: view.topAnchor),
canvas.bottomAnchor.constraint(equalTo: view.bottomAnchor)])
toolPicker.setVisible(true, forFirstResponder: canvas)
toolPicker.addObserver(canvas)
canvas.delegate = self
canvas.becomeFirstResponder()
if let drawing = try? PKDrawing(data: drawingData){
canvas.drawing = drawing
}
}
}

Related

Swift UI: UIHostingController.view is not fit to content view size at iOS 13

I want to update Swift UI View according to the communication result.
But UIHostingController.view is not fit rootView size at iOS 13.
The same thing happens when I try with the sample code below.
I want to add self-sizing SwiftUI View to UIStackView, but SwiftUI View overlaps with the previous and next views is occurring because this problem.
How can I avoid this problem?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let object = SampleObject()
let sampleView = SampleView(object: object)
let hosting = UIHostingController(rootView: sampleView)
hosting.view.backgroundColor = UIColor.green
addChild(hosting)
view.addSubview(hosting.view)
hosting.view.translatesAutoresizingMaskIntoConstraints = false
hosting.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
hosting.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
hosting.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
hosting.didMove(toParent: self)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
object.test()
}
}
}
struct SampleView: View {
#ObservedObject var object: SampleObject
var body: some View {
VStack {
Text("test1").background(Color.blue)
Text("test2").background(Color.red)
if object.state.isVisibleText {
Text("test2").background(Color.gray)
}
}
.padding(32)
.background(Color.yellow)
}
}
final class SampleObject: ObservableObject {
struct ViewState {
var isVisibleText: Bool = false
}
#Published private(set) var state = ViewState()
func test() {
state.isVisibleText = true
}
}
If addSubview to UIStackView as below, the height of Swift UI View will not change in iOS13.
iOS13 (incorrect)
iOS14 (correct)
You have not set the bottom anchor, add this line
hosting.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
Another easy way is to set frame to hosting controller view and remove the constraint.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let object = SampleObject()
let sampleView = SampleView(object: object)
let hosting = UIHostingController(rootView: sampleView)
hosting.view.frame = UIScreen.main.bounds //<---here
hosting.view.backgroundColor = UIColor.green
addChild(hosting)
view.addSubview(hosting.view)
hosting.didMove(toParent: self)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
object.test()
}
}
}
Only for iOS 13
Try this:
Every time the view size change, call this:
sampleView.view.removeFromSuperview()
let sampleView = SampleView(object: object)
let hosting = UIHostingController(rootView: sampleView)
view.addArrangedSubview(hosting.view)

error "Value of type 'UIViewController' has no member..." when moving a func inside extension

I need to move a method for adding and removing a logging view inside an Extension, in order to give it to every controller. to do so I added a inout UIVew parameter to original method, where I used a global var for the view. no I have this error
Value of type 'UIViewController' has no member 'containerForLoading'
removing self from self.containerForLoading will give error:
Escaping closure captures 'inout' parameter 'containerForLoading'
inside the animate closure (see the comment)
is all wrong the entire process or I am lost at the last step?
extension UIViewController {
func showLoadingView(containerForLoading: inout UIView, uponView: UIView) {
containerForLoading = UIView(frame: uponView.bounds)
uponView.addSubview(containerForLoading)
containerForLoading.backgroundColor = .white
containerForLoading.alpha = 0
UIView.animate(withDuration: 0.24) { self.containerForLoading.alpha = 0.8 } //here the error
let activivityIndicator = UIActivityIndicatorView()
containerForLoading.addSubview(activivityIndicator)
activivityIndicator.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
activivityIndicator.centerYAnchor.constraint(equalTo: uponView.centerYAnchor),
activivityIndicator.centerXAnchor.constraint(equalTo: uponView.centerXAnchor)
])
activivityIndicator.startAnimating()
}
func removeLoading(containerForLoading: inout UiView, uponView: UIView) {
containerForLoading.removeFromSuperview()
}
}
this is the code inside the original viewController
using this var
var containerForLoading = UIView()
called this way when needed
self.showLoadingView(uponView: self.view)
extension ViewController {
func showLoadingView(uponView: UIView) {
containerForLoading = UIView(frame: uponView.bounds)
uponView.addSubview(containerForLoading)
containerForLoading.backgroundColor = .white
containerForLoading.alpha = 0
UIView.animate(withDuration: 0.24) { self.containerForLoading.alpha = 0.8 }
let activivityIndicator = UIActivityIndicatorView()
containerForLoading.addSubview(activivityIndicator)
activivityIndicator.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
activivityIndicator.centerYAnchor.constraint(equalTo: uponView.centerYAnchor),
activivityIndicator.centerXAnchor.constraint(equalTo: uponView.centerXAnchor)
])
activivityIndicator.startAnimating()
}
func removeLoading(uponView: UIView) {
containerForLoading.removeFromSuperview()
}
}
You could make loadingContainerTag a local variable, and change the parameter name to something else. Then assign to the parameter just after you create the container view:
extension UIViewController {
func showLoadingView(containerForLoadingProperty: inout UIView, uponView: UIView) {
// local variable!
let containerForLoading = UIView(frame: uponView.bounds)
// also set property
containerForLoadingProperty = containerForLoading
uponView.addSubview(containerForLoading)
containerForLoading.backgroundColor = .white
containerForLoading.alpha = 0
// no "self."!
UIView.animate(withDuration: 0.24) { containerForLoading.alpha = 0.8 }
// ... everything else is the same
removeLoading could just have one non-inout parameter:
func removeLoading(containerForLoadingProperty: UIView) {
containerForLoadingProperty.removeFromSuperview()
}
But...
It is very weird for a method that shows a loading indicator, to need an inout parameter. It shouldn't assign to a special property that the caller provides. It should just show the loading indicator!
The purpose of your containerForLoading property is so that in removeLoading, you know which view to remove. If you don't store the containerForLoading view somewhere in a property, you wouldn't know which view to remove, right? Well, we can use the tag property of a view to identify views, so you can just make containerForLoading a local variable, and later in removeLoading, use its tag to find it.
extension UIViewController {
static let loadingContainerTag = <a number you like>
func showLoadingView(uponView: UIView) {
// local variable!
let containerForLoading = UIView(frame: uponView.bounds)
uponView.addSubview(containerForLoading)
containerForLoading.backgroundColor = .white
containerForLoading.alpha = 0
// set tag
containerForLoading.tag = UIViewController.loadingContainerTag
// no "self."!
UIView.animate(withDuration: 0.24) { containerForLoading.alpha = 0.8 }
let activivityIndicator = UIActivityIndicatorView()
containerForLoading.addSubview(activivityIndicator)
activivityIndicator.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
activivityIndicator.centerYAnchor.constraint(equalTo: uponView.centerYAnchor),
activivityIndicator.centerXAnchor.constraint(equalTo: uponView.centerXAnchor)
])
activivityIndicator.startAnimating()
}
func removeLoading(uponView: UIView) {
// find view with the tag
uponView.viewWithTag(UIViewController.loadingContainerTag)?.removeFromSuperview()
}
}

Center UILabel created in code using Swift

This may be the simplest thing you can possibly due in Xcode in Swift and for some reason, it is not working properly.
I want to center a label in a view. The only other thing in the view previously was a webView added programatically but for now I have removed that so basically, I have an empty VC in which I'm trying to center a label.
There are umpteen answers on SO about this and I've tried every combination but can't get it to to work.
Can anyone suggest a foolproof way to accomplish the simple task of centering a UILabel?
Below is the code I currently have and steps I've taken along with result:
I created an empty view controller in Storyboard and embedded it in a navigation controller.
I set the View Controller in Storyboard to my swift VC class. I also have already cleaned project, closed and re-opened XCode and also deleted storyboard and recreated it in case it was corrupted. Still nothing works.
myVC.swift
import UIKit
class myVC: UIViewController,WKScriptMessageHandler, WKNavigationDelegate,WKUIDelegate {
var title= "Hello there"
var loadingLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
webView.uiDelegate = self
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
// loadingLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
// loadingLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
// loadingLabel = UILabel(frame: CGRect(x: 0, y: self.view.center.y, width: 290, height: 70))
loadingLabel.center = self.view.center
loadingLabel.textAlignment = .center
loadingLabel.font = UIFont(name: "Halvetica", size: 18.0)
loadingLabel.numberOfLines = 0
loadingLabel.text = "TEXT I WANT TO CENTER"
loadingLabel.lineBreakMode = .byTruncatingTail
loadingLabel.center = self.view.center
self.view.addSubview(loadingLabel)
self.title = title
}
override func loadView() {
super.loadView()
}
}
Add the loadingLabel as subview before adding the constraints.
view.addSubview(loadingLabel)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loadingLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

change all view controller background in swift

I am working on my project app where I want to allow my user to change the background wallpaper to be same on all screens. I have a settings screen where I am adding that. I have added ImageViews to all view controllers and I have some view controllers that have UIscrollview so I added Imageview to slides template. Now my dilemma is how can I allow the user to pick the preview wallpaper so it changes the Imageview image on every view controller. I already created such #IBOutlets as shown below.
#IBOutlet weak var slideBackground: UIImageView!
#IBOutlet weak var homeScreenBackground: UIImageView!
#IBOutlet weak var settingsBackground: UIImageView!
You should use the system wide NotificationCenter.
Simply put, you can have objects subscribe to the default NotificationCenter and specify a selector (method) to execute when a notification is posted.
You can also post custom notifications that represent the wallpaper change event.
I have used this in an app I built to achieve a system wide 'dark mode' transition.
To post:
#objc func postWallpaperChangeNotification() {
NotificationCenter.default.post(name: .wallpaperChanged, object: nil)
}
To subscribe:
NotificationCenter.default.addObserver(self, selector: #selector(someMethodToRunWhenWallpaperChanges(_:)), name: . wallpaperChanged, object: nil)
You also need to remove the observer in deinit().
This is approximate code to give you a flavour, any questions hmu.
You have a few options.. what option is best depends on your needs really.
As Woodstock mentioned in his answer, you could use NotificationCentre, I wont re-explain that.
Another option would be to store the image name in UserDefaults that you are going to use for the background image.
any time you change the background... set the value
UserDefaults.standard.set(imageName, forKey "backgroundImageName")
Then in each view controller, just load the value on viewWillAppear
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated: animated)
if let backgroundImageName = UserDefaults.standard.string(forKey: "backgroundImageName") {
self.backgroundImageView.image = UIImage(named: backgroundImageName)
}
}
Both of these options are not very easy to unit test though. You could use Mocks to test it.
A bonus of this method is that it will 'remember' the setting inbetween the user restarting the app.
An example of how you might reduce code repetition using subclassing:
class WallpaperedViewController: UIViewController {
lazy private var imageView: UIImageView = {
let imageView = UIImageView()
view.addSubview(imageView)
view.sendSubview(toBack: imageView)
return imageView
}()
private func setWallPaperImage() {
let imageName = UserDefaults.standard.string(forKey: "backgroundImageName")
let image = UIImage(named: imageName!)
imageView.image = image
//imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setWallPaperImage()
}
}
Then for each ViewController that has this background image wallpaper just extend this class:
class SomeViewController: WallpaperedViewController {}

CALayer appears only for one second, then disappears

I'm adding CALayer to top and bottom of scrollable objects (UIScrollView, TableView, CollectionView) to display them when there is a content behind the visible area.
class TableViewWithCALayers: UITableView {
var topGradientLayer: CAGradientLayer?
var bottomGradientLayer: CAGradientLayer?
override func layoutSubviews() {
super.layoutSubviews()
guard self.topGradientLayer != nil && self.bottomGradientLayer != nil else {
addGradientLayerToTop() // create layer, set frame, etc.
addGradientLayerToBottom()
return
}
// addGradientLayerToTop()// if uncomment it - multiple layers are created and they are visible, but this is not the solution...
handleLayerAppearanceAfterLayoutSubviews() // playing with opacity here
}
How I create layer:
func addGradientLayerToTop() {
if let superview = superview {
self.topGradientLayer = CAGradientLayer()
let colorTop = UIColor.redColor().CGColor
let colorBottom = UIColor.clearColor().CGColor
if let topLayer = self.topGradientLayer {
topLayer.colors = [colorTop, colorBottom]
topLayer.locations = [0.0, 1.0]
topLayer.frame = CGRect(origin: self.frame.origin, size: CGSizeMake(self.frame.width, self.layerHeight))
superview.layer.insertSublayer(topLayer, above: self.layer)
if (self.contentOffset.y == 0) {
// if we are at the top - hide layer
// topLayer.opacity = 0.0 //temporarily disabled, so it is 1.0
}
}
}
}
TableViewWithCALayers works nice everywhere, except using TableView with xib files:
class XibFilesViewController : CustomUIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: TableViewWithCALayers!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "CustomTableViewCell")
self.tableView.layer.masksToBounds = false // this line doesn't help...
}
CustomUIViewController is used in many other ViewControllers where TableViewWithCALayers works good, so it should not create a problem.
Layers at the top and bottom appear for one second, then disappear. Logs from LayoutSubviews() func say that they are visible and opacity are 1.0, but something covers them. What can it be and how to deal with that?
Any help is appreciated!)
topLayer.zPosition = 10000 //doesn't help
topLayer.masksToBounds = false //doesn't help as well
When using nib files it's good practice, and design to add the UIView that you want to draw the layer on into your prototype cell, or header/footed and then have that view confirm to your class that's actually handling the layer.

Resources