I have two of the StoryBoards containing TextFields and two Buttons.
The second StoryBoard has an ImageView received from the first StoryBoard.
I want to make the text in the TextField on the ImageView in the second StoryBoard and then convert it to a PDF file.
I found this code on the site and tried to use it, but I really did not know how to use it and I could not do that. Can someone help me?
import UIKit
import PDFKit
class ViewController: UIViewController {
#IBOutlet weak var textview: UITextField!
#IBOutlet weak var imageview1: UIImageView!
let PdfView = pdfViewController()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Button To send Data To Another view
#IBAction func aa(_ sender: Any)
{
let label = UILabel(frame: CGRect(x: 20, y: 20, width: 80, height: 30))
label.text = "Hello ...!"
label.font = UIFont.systemFont(ofSize: 20)
label.textColor = .black
view.addSubview(label)
sample1(label: label)
//sample2(label: label)
//sample3(label: label)
//sample4(label: label)
PdfView.imageview.clipsToBounds = true
view.addSubview(PdfView.imageview)
}
func sample1(label: UILabel) {
PdfView.imageview.contentMode = .scaleAspectFit
PdfView.imageview.image = UIImage(named: "AR1-1")?.with(view: label) { (parentSize, viewToAdd) in
print("parentSize: \(parentSize)")
viewToAdd.font = UIFont.systemFont(ofSize: 40)
viewToAdd.textColor = .yellow
viewToAdd.bounds = CGRect(x: 40, y: 40, width: 200, height: 40)
}
}
// Button To Move To Another View
#IBAction func ww(_ sender: Any)
{
}
}
extension UIView {
func copyObject<T: UIView> () -> T? {
let archivedData = NSKeyedArchiver.archivedData(withRootObject: self)
return NSKeyedUnarchiver.unarchiveObject(with: archivedData) as? T
}
}
extension UIImage {
typealias EditSubviewClosure<T: UIView> = (_ parentSize: CGSize, _ viewToAdd: T)->()
func with<T: UIView>(view: T, editSubviewClosure: EditSubviewClosure<T>) -> UIImage {
if let copiedView = view.copyObject() as? T {
UIGraphicsBeginImageContext(size)
let basicSize = CGRect(origin: .zero, size: size)
draw(in: basicSize)
editSubviewClosure(size, copiedView)
copiedView.draw(basicSize)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
return self
}
}
extension UIImageView {
enum ImageAddingMode {
case changeOriginalImage
case addSubview
case addCopiedSubview
}
func drawOnCurrentImage<T: UIView>(view: T, mode: ImageAddingMode, editSubviewClosure: #escaping UIImage.EditSubviewClosure<T>) {
guard let image = image else {
return
}
let addSubView: (T) -> () = { view in
editSubviewClosure(self.frame.size, view)
self.addSubview(view)
}
switch mode {
case .changeOriginalImage:
self.image = image.with(view: view, editSubviewClosure: editSubviewClosure)
case .addSubview:
addSubView(view)
case .addCopiedSubview:
if let copiedView = view.copyObject() as? T {
addSubView(copiedView)
}
}
}
}
/
import UIKit
import PDFKit
class pdfViewController: UIViewController {
#IBOutlet weak var imageview: UIImageView!
let me = ViewController()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
#IBAction func sendbutton(_ sender: Any)
{
}
}
Related
Why can't I use other pencils or colors as expected in this app? It only draws a black color. This is my code:
import UIKit
import PencilKit
import PhotosUI
class ViewController: UIViewController, PKCanvasViewDelegate, PKToolPickerObserver {
#IBOutlet weak var pencilButton: UIBarButtonItem!
#IBOutlet weak var canvasView: PKCanvasView!
let canvasWidth: CGFloat = 768
let canvasOverScrollHeight: CGFloat = 500
let drawing = PKDrawing()
override func viewDidLoad() {
super.viewDidLoad()
canvasView.drawing = drawing
canvasView.delegate = self
canvasView.alwaysBounceVertical = true
canvasView.drawingPolicy = .anyInput
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let toolPicker = PKToolPicker()
toolPicker.setVisible(true, forFirstResponder: canvasView)
toolPicker.addObserver(canvasView)
canvasView.becomeFirstResponder()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let canvasScale = canvasView.bounds.width / canvasWidth
canvasView.minimumZoomScale = canvasScale
canvasView.maximumZoomScale = canvasScale
canvasView.zoomScale = canvasScale
updateContentSizeForDrawing()
canvasView.contentOffset = CGPoint(x: 0, y: -canvasView.adjustedContentInset.top)
}
override var prefersHomeIndicatorAutoHidden: Bool{
return true
}
#IBAction func fingerOrPencil (_ sender: Any) {
canvasView.allowsFingerDrawing.toggle()
pencilButton.title = canvasView.allowsFingerDrawing ? "Finger" : "Pencil"
}
#IBAction func saveToCameraRoll(_ sender: Any) {
UIGraphicsBeginImageContextWithOptions(canvasView.bounds.size, false, UIScreen.main.scale)
canvasView.drawHierarchy(in: canvasView.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if image != nil {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image!)
}, completionHandler: {success, error in
})
}
}
func updateContentSizeForDrawing() {
let drawing = canvasView.drawing
let contentHeight: CGFloat
if !drawing.bounds.isNull {
contentHeight = max(canvasView.bounds.height, (drawing.bounds.maxY + self.canvasOverScrollHeight) * canvasView.zoomScale)
} else {
contentHeight = canvasView.bounds.height
}
canvasView.contentSize = CGSize(width: canvasWidth * canvasView.zoomScale, height: contentHeight)
}
// Delegate Methods
func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
updateContentSizeForDrawing()
}
func canvasViewDidEndUsingTool(_ canvasView: PKCanvasView) {
}
func canvasViewDidFinishRendering(_ canvasView: PKCanvasView) {
}
func canvasViewDidBeginUsingTool(_ canvasView: PKCanvasView) {
}
}
These are the outputs in the console:
2023-01-04 18:34:04.429420+0300 Drawing[45460:449613] [Assert] UINavigationBar decoded as unlocked for UINavigationController, or navigationBar delegate set up incorrectly. Inconsistent configuration may cause problems. navigationController=<UINavigationController: 0x123024000>, navigationBar=<UINavigationBar: 0x12140a0a0; frame = (0 47; 0 50); opaque = NO; autoresize = W; layer = <CALayer: 0x6000030afae0>> delegate=0x123024000
2023-01-04 18:34:04.468831+0300 Drawing[45460:449613] Metal API Validation Enabled
2023-01-04 18:34:04.705019+0300 Drawing[45460:449613] [ToolPicker] Missing defaults dictionary to restore state for: PKPaletteNamedDefaults
2023-01-04 18:35:00.196200+0300 Drawing[45460:449613] Keyboard cannot present view controllers (attempted to present <UIColorPickerViewController: 0x121846e00>)
toolPicket released when out of method scope.
You should have a instance of toolPicker in ViewController.
class ViewController: UIViewController {
let toolPicker = PKToolPicker()
...
}
i solved my problem by changing
toolPicker.addObserver(self)
into
toolPicker.addObserver(canvasView)
and adding the toolPicker at the top as #noppefoxwolf suggested
I'm a newbie, and I'm practicing. I have an app with 3 imageView (Create Avatar App). I want that when I press the button, an image is saved, with the 3 custom imageview. The code I have is the following:
#IBAction func saveImageMen (_ sender: Any) {
}
extension UIView{
func createTransparentImage () -> UIImage {
let renderFormat = UIGraphicsImageRendererFormat.default ()
renderFormat.opaque = false
self.isOpaque = false
self.layer.isOpaque = true
self.backgroundColor = UIColor.clear
self.layer.backgroundColor = UIColor.clear.cgColor
let renderer = UIGraphicsImageRenderer (size: bounds.size, format: renderFormat)
return renderer.image {
(context) in
layer.render (in: context.cgContext)
}
}
}
I don't know how to run this extension when the button is pressed
Since you want to render an image, you can create extension for UIImageView as this is derived from UIView something below, this will render image on click of the button:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func renderImage(_ sender: Any) {
imageView.createTransparentImage()
}
}
extension UIImageView {
func createTransparentImage () {
let renderFormat = UIGraphicsImageRendererFormat.default ()
renderFormat.opaque = false
self.isOpaque = false
self.layer.isOpaque = true
self.backgroundColor = UIColor.black
self.layer.backgroundColor = UIColor.black.cgColor
let renderer = UIGraphicsImageRenderer (size: bounds.size, format: renderFormat)
self.image = renderer.image {
(context) in
layer.render (in: context.cgContext)
}
}
}
So it is an extension of UIView class and you can call a function with an instance of the class so here you go:
UIView().createTransparentImage()
This will return the image so user it something like above:
let image = UIView().createTransparentImage()
I have a simple media player and I'm trying to make it change the artwork image as the songs change. With the code I have now it will display the artwork when you hit play but when I hit the next button to skip to the next item it stays the same unless you hit another button.
How can I make the UIImageView image change as the song media item changes?
import UIKit
import MediaPlayer
class ViewController: UIViewController {
#IBOutlet weak var coverImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createQueue()
}
func showArt(){
coverImageView.image =
myMediaPlayer.nowPlayingItem?.artwork!.image(at: CGSize.init(width: 500, height: 500))
coverImageView.isUserInteractionEnabled = true
}
#IBAction func playButton(_ sender: UIButton) {
togglePlay(on: sender)
showArt()
}
#IBAction func backButton(_ sender: UIButton) {
back()
}
#IBAction func nextButton(_ sender: UIButton) {
skip()
}
}
My other functions are as followed:
import MediaPlayer
let myMediaPlayer = MPMusicPlayerApplicationController.systemMusicPlayer
let playDrake = MPMediaPropertyPredicate(value: "Drake", forProperty: MPMediaItemPropertyArtist, comparisonType: MPMediaPredicateComparison.equalTo)
let myFilterSet: Set<MPMediaPropertyPredicate> = [playDrake]
func createQueue() {
let drakeQuery = MPMediaQuery(filterPredicates: myFilterSet)
myMediaPlayer.setQueue(with: drakeQuery)
}
func skip() {
myMediaPlayer.skipToNextItem()
}
func back() {
if myMediaPlayer.currentPlaybackTime > 0.05 {
myMediaPlayer.skipToPreviousItem()
} else if myMediaPlayer.currentPlaybackTime < 0.05 {
myMediaPlayer.skipToBeginning()
} else {
//do nothing
}
}
func togglePlay(on: UIButton) {
if myMediaPlayer.playbackState.rawValue == 2 || myMediaPlayer.playbackState.rawValue == 0 {
on.setTitle("Pause", for: UIControlState.normal)
myMediaPlayer.play()
} else if myMediaPlayer.playbackState.rawValue == 1{
on.setTitle("Play", for: UIControlState.normal)
myMediaPlayer.pause()
} else {
// do nothing
}
}
Try loading the image asynchronously
DispatchQueue.global(qos: .background).async {
myMediaPlayer.nowPlayingItem?.artwork!.image(at: CGSize.init(width: 500, height: 500))
}
I have VPMOTPView custom view in my `.xib' like this.
class VerifyOTP: UIView {
#IBOutlet weak var otpView: VPMOTPView!
var emailID = ""
var userID = ""
#IBAction func resendOTPAction(_ sender: UIButton) {
print("asdds")
}
override func awakeFromNib() {
super.awakeFromNib()
otpView.otpFieldsCount = 4
otpView.otpFieldDefaultBorderColor = UIColor.blue
otpView.otpFieldEnteredBorderColor = UIColor.red
otpView.otpFieldBorderWidth = 2
otpView.delegate = self
// Create the UI
otpView.initalizeUI()
}
}
extension VerifyOTP: VPMOTPViewDelegate {
func hasEnteredAllOTP(hasEntered: Bool) {
print("Has entered all OTP? \(hasEntered)")
}
func enteredOTP(otpString: String) {
print("OTPString: \(otpString)")
}
}
Then in my 'ViewController'
var verifyOTPView: VerifyOTP?
self.verifyOTPView = VerifyOTP.fromNib()
self.verifyOTPView?.frame = CGRect(x: 20, y: 0, width: screenSize.width - 40, height: screenSize.height / 3)
self.view.addSubview(self.verifyOTPView!)
But by this I can see my RESEND OTP button on screen but OTPVIEW is not displayed.
From the screenshot it doesn't look like you have any constraints set up for your views?
If not try adding constraints and see if that fixes the problem.
I am trying to display a button on the MainViewController and a UITextField in an ExternalViewController for when the device is connected via HDMI. When a click occurs in the MainViewController, I need to update the UITextField in the ExternalViewController. I can see the prints occur in the output window, but the text field does not update.
MainViewController.swift
import UIKit
import WebKit
class MainViewController: UIViewController {
fileprivate var externalWindow: UIWindow?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if UIScreen.screens.count > 1 {
setupExternalScreen(UIScreen.screens[1])
}
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = UIColor.blue
button.setTitle("Click Me", for: UIControlState.normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
fileprivate func setupExternalScreen(_ screen: UIScreen) {
guard externalWindow == nil,
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ExternalScreen") as? ExternalViewController else {
return
}
externalWindow = UIWindow(frame: screen.bounds)
externalWindow!.rootViewController = vc
externalWindow!.screen = screen
externalWindow!.isHidden = false
}
func buttonAction(sender: UIButton) {
print("Button tapped")
ExternalViewController().updateLabel()
}
}
ExternalViewController.swift
import UIKit
class ExternalViewController: UIViewController {
let output = UITextField(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 300, height: 100)))
override func viewDidLoad() {
super.viewDidLoad()
self.addTextField()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addTextField() {
output.textColor = UIColor.black
output.text = "This is the other text field"
view.addSubview(output)
}
func updateLabel() {
print("inside updateLabel")
output.text = "button was clicked"
}
}
This is how it looks like.
This is my first project with Swift, so I apologize if it is a bad question.
Try using NotificationCentre .
In ExternalVC
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(receivedDataFromNotification(notification:)), name: NSNotification.Name(rawValue: "passdata"), object: nil)
}
func receivedDataFromNotification(notification : NSNotification) -> Void {
print(notification.object);
output.text = "button was clicked"
}
In MainViewController
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "passdata"), object: "your string pass here")
While you can use a notification to transfer data between I prefer creating a delegate to transfer the data.
first create a protocol
protocol ExternalViewControllerDelegate: class{
func shouldUpdateLabel(withText text: String)
}
Then update the ExternalViewController appropriately to contain the delegate which a weak reference of course
class ExternalViewController: UIViewController {
weak var delegate: ExternalViewControllerDelegate?
let output = UITextField(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 300, height: 100)))
override func viewDidLoad() {
super.viewDidLoad()
self.addTextField()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addTextField() {
output.textColor = UIColor.black
output.text = "This is the other text field"
view.addSubview(output)
}
func updateLabel() {
print("inside updateLabel")
output.text = "button was clicked"
delegate?.shouldUpdateLabel(withText: "Your text")
}
}
Remember to call the method in the delegate. I used the updateLabel method in the class to call the method. Which I assume you also want to use
Finally implement the protocol in the MainViewController and remember to set the delegate.
extension MainViewController: ExternalViewControllerDelegate{
func shouldUpdateLabel(withText text: String) {
//Do what you want with the text
}
}
Then update the setupExternalScreen method to set the delegate
func setupExternalScreen(_ screen: UIScreen) {
guard externalWindow == nil,
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ExternalScreen") as? ExternalViewController else {
return
}
vc.delegate = self
externalWindow = UIWindow(frame: screen.bounds)
externalWindow!.rootViewController = vc
externalWindow!.screen = screen
externalWindow!.isHidden = false
}