i add about 20+ images to the stack and by tap on image i need to change borderColor, but with this code i have error " "-[__NSArray0 tapOnView]: unrecognized selector sent to instance "
Add stack here
private lazy var mainHStack: UIStackView = {
let stack = UIStackView()
stack.axis = .horizontal
stack.distribution = .fill
stack.spacing = 8
return stack
}()
Add constraints here
scrollView.addSubview(mainHStack)
mainHStack.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
tapOnMediaView()
Configure stack here
func configureMediaViewer(withImages images: [String]) {
for image in images {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 8
imageView.clipsToBounds = true
imageView.setImage(imageUrl: image)
mainHStack.addArrangedSubview(imageView)
imageView.snp.makeConstraints { make in
make.width.height.equalTo(60)
}
}
}
Check if i tapped on image here
func tapOnMediaView() {
let arrangedImages = mainHStack.arrangedSubviews
let tap = UITapGestureRecognizer(target: arrangedImages, action: #selector(tapOnView))
if let tag = tap.view?.tag {
let currentImage = mainHStack.arrangedSubviews[tag]
currentImage.layer.borderWidth = 1
currentImage.layer.borderColor = UIColor.orange.cgColor
}
addGestureRecognizer(tap)
}
TapOnView has a delegate
#objc func tapOnView() {
delegate?.tapOnView()
}
Delegate
protocol PhotosViewProtocol: AnyObject {
func tapOnView()
}
Extension for mainVC
extension MediaViewerViewController: PhotosViewProtocol {
func tapOnView() {
print("check if works")
//not works :C
}
}
how do i change my code to get a result?
Related
I am trying to zoom image view inside a UIView, but it zoom outside the UIView.
Condition : without using scrollview
here is my code :
extension UIImageView {
func enableZoom() {
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(startZooming(_:)))
isUserInteractionEnabled = true
addGestureRecognizer(pinchGesture)
}
#objc
private func startZooming(_ sender: UIPinchGestureRecognizer) {
let scaleResult = sender.view?.transform.scaledBy(x: sender.scale, y: sender.scale)
guard let scale = scaleResult, scale.a > 1, scale.d > 1 else { return }
sender.view?.transform = scale
sender.scale = 1
}
}
lazy var ImgView : UIImageView = {
let i = UIImageView()
i.enableZoom()
return i
}()
lazy var topView : UIView = {
let c = UIView()
return c
}()
in viewdidload
self.view.layout(self.ImgView).top(90).left().right().height(topViewHeight)
self.topView = self. ImgView
I make drawing book apps. And I made pencilKit in swift So as an image that I add in this question.
So I can draw several things on the canvasView. But!!! I really wanna take pictures in the photo roll so I wanna use that as the background of my canvasView.
But if canvasView.addSubview(ImageView) is in the code then my gray ImageView is bo on the top of my canvasView so if I draw things, then that things are drawn under the canvasView.
If I use imageView.sendSubviewToBack(canvasView) then nothing happen. I really did know how to insert my background image between RootView and canvasView.
Here are my image and code.
//
// ViewController.swift
// webtoon
//
// Created by 신효근 on 2020/07/13.
// Copyright © 2020 신효근. All rights reserved.
//
import UIKit
import PencilKit
class ViewController: UIViewController, PKCanvasViewDelegate, PKToolPickerObserver {
#IBOutlet weak var canvasView: PKCanvasView!
let canvasWidth : CGFloat = 768
let canvasOverscrollHight : CGFloat = 500
var imageView = UIImageView()
var drawing = PKDrawing()
let picker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
canvasView.delegate = self
canvasView.drawing = drawing
canvasView.alwaysBounceVertical = true
canvasView.allowsFingerDrawing = true
if let window = parent?.view.window,
let toolPicker = PKToolPicker.shared(for: window){
toolPicker.setVisible(true, forFirstResponder:canvasView)
toolPicker.addObserver(canvasView)
canvasView.becomeFirstResponder()
}
self.imageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 500)
self.imageView.backgroundColor = .gray
imageView.sendSubviewToBack(canvasView)
}
// override func viewDidLayoutSubviews() {
// let canvasScale = canvasView.bounds.width/canvasWidth
// canvasView.minimumZoomScale = canvasScale
// canvasView.maximumZoomScale = canvasScale
// canvasView.zoomScale = canvasScale
// }
override var prefersHomeIndicatorAutoHidden: Bool {
return true
}
#IBAction func saveDrawingToCameraRoll(_ sender: Any) {
}
#IBAction func addButtonPressed(_ sender: Any) {
self.present(self.picker, animated: true)
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var newImage: UIImage? = nil
print("Start")
print(info)
print("end")
if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage { // 수정된 이미지가 있을 경우
newImage = possibleImage
} else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { // 오리지널 이미지가 있을 경우
newImage = possibleImage
}
imageView.image = newImage // 받아온 이미지를 이미지 뷰에 넣어준다.
picker.dismiss(animated: true) // 그리고 picker를 닫아준다.
}
}
Here is my code it works for me
canvasView.isOpaque = false
canvasView.backgroundColor = UIColor.clear
canvasView.delegate = context.coordinator
canvasView.becomeFirstResponder()
let imageView = UIImageView(image: canvasImage)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
let contentView = canvasView.subviews[0]
contentView.addSubview(imageView)
contentView.sendSubviewToBack(imageView)
I'm trying to create a cell that contains a square UIImageView and a UITextField. If the text fits the width of the screen, then everything works fine. But as soon as I change the text to a longer one, the presentation breaks down. There are no messages in the console about the correctness of the constraints.
When the text in the UITextField fits on the screen or UITextField contains only placeholder everything works fine.
But if the text is long enough, the presentation breaks down.
The code with which I create the view:
extension TextFieldWithImageTVCell {
private func initView() {
selectionStyle = .none
initImgView()
initTextField()
contentView.addSubview(imgView)
contentView.addSubview(textField)
// debug code
imgView.backgroundColor = UIColor.black
textField.backgroundColor = UIColor.blue
}
private func initImgView() {
imgView = UIImageView(frame: CGRect.zero)
imgView.translatesAutoresizingMaskIntoConstraints = false
}
private func initTextField() {
textField = UITextField(frame: CGRect.zero)
textField.translatesAutoresizingMaskIntoConstraints = false
textField.isUserInteractionEnabled = false
}
}
The code with which I create constraints:
extension TextFieldWithImageTVCell {
private func initConstraints() {
initConstraintsImgView()
initConstraintsTextField()
}
private func initConstraintsImgView() {
imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor).isActive = true
let margins = contentView.layoutMarginsGuide
imgView.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
imgView.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
imgView.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
}
private func initConstraintsTextField() {
textField.leadingAnchor.constraint(equalTo: imgView.trailingAnchor, constant: 8).isActive = true
let margins = contentView.layoutMarginsGuide
textField.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
textField.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
textField.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
}
}
The part of code with which I configure cell:
cell.textContent = subject
cell.placeholder = "Предмет"
cell.isEditingEnabled = true
guard let textField = cell.textField else {
assertionFailure("error in ItemSubject::configureCellForRow")
return
}
textField.delegate = self
textField.clearButtonMode = .always
textField.adjustsFontSizeToFitWidth = true
textField.minimumFontSize = 10
Cell properties:
extension TextFieldWithImageTVCell {
var placeholder: String? {
set { textField.placeholder = newValue }
get { return textField.placeholder }
}
var textContent: String? {
set { textField.text = newValue }
get { return textField.text }
}
var isEditingEnabled: Bool {
set { textField.isUserInteractionEnabled = newValue }
get { return textField.isUserInteractionEnabled }
}
}
What constraints do I need to add to achieve the desired result?
Why are my constraints not enough?
I have a custom view subclassing NSView, which is just an NSStackView containing a label, slider, a second label and a checkbox. The slider and checkbox are both configured to report changes to the view (and eventually, via a delegate to a ViewController):
fileprivate extension NSTextField {
static func label(text: String? = nil) -> NSTextField {
let label = NSTextField()
label.isEditable = false
label.isSelectable = false
label.isBezeled = false
label.drawsBackground = false
label.stringValue = text ?? ""
return label
}
}
#IBDesignable
class Adjustable: NSView {
private let sliderLabel = NSTextField.label()
private let slider = NSSlider(target: self, action: #selector(sliderChanged(_:)))
private let valueLabel = NSTextField.label()
private let enabledCheckbox = NSButton(checkboxWithTitle: "Enabled", target: self, action: #selector(enabledChanged(_:)))
var valueFormatter: (Double)->(String) = { String(format:"%5.2f", $0) }
...
#objc func sliderChanged(_ sender: Any) {
guard let slider = sender as? NSSlider else { return }
valueLabel.stringValue = valueFormatter(slider.doubleValue)
print("Slider now: \(slider.doubleValue)")
delegate?.adjustable(self, changedValue: slider.doubleValue)
}
#objc func enabledChanged(_ sender: Any) {
guard let checkbox = sender as? NSButton else { return }
print("Enabled now: \(checkbox.state == .on)")
delegate?.adjustable(self, changedEnabled: checkbox.state == .on)
}
}
Using InterfaceBuilder, I can add one instance of this to a ViewController by dragging in a CustomView and setting it's class in the Identity Inspector. Toggling the checkbox or changing the slider will have the desired effect.
However, if I have multiple instances then in the target-action functions self will always refer to the same instance of the view, rather than the one being interacted with. In other words, self.slider == sender is only true in sliderChanged for one of the sliders. While I can get the correct slider value via sender, I cannot update the correct label as self.valueLabel is always the label in the first instance of the custom view.
Incidentally, #IBDesignable and the code intended to support it have no effect so there's something I'm missing there too - Interface Builder just shows empty space.
The whole file:
import Cocoa
fileprivate extension NSTextField {
static func label(text: String? = nil) -> NSTextField {
let label = NSTextField()
label.isEditable = false
label.isSelectable = false
label.isBezeled = false
label.drawsBackground = false
label.stringValue = text ?? ""
return label
}
}
protocol AdjustableDelegate {
func adjustable(_ adjustable: Adjustable, changedEnabled: Bool)
func adjustable(_ adjustable: Adjustable, changedValue: Double)
}
#IBDesignable
class Adjustable: NSView {
var delegate: AdjustableDelegate? = nil
private let sliderLabel = NSTextField.label()
private let slider = NSSlider(target: self, action: #selector(sliderChanged(_:)))
private let valueLabel = NSTextField.label()
private let enabledCheckbox = NSButton(checkboxWithTitle: "Enabled", target: self, action: #selector(enabledChanged(_:)))
var valueFormatter: (Double)->(String) = { String(format:"%5.2f", $0) }
#IBInspectable
var label: String = "" {
didSet {
sliderLabel.stringValue = label
}
}
#IBInspectable
var value: Double = 0 {
didSet {
slider.doubleValue = value
valueLabel.stringValue = valueFormatter(value)
}
}
#IBInspectable
var enabled: Bool = false {
didSet {
enabledCheckbox.isEnabled = enabled
}
}
#IBInspectable
var minimum: Double = 0 {
didSet {
slider.minValue = minimum
}
}
#IBInspectable
var maximum: Double = 100 {
didSet {
slider.maxValue = maximum
}
}
#IBInspectable
var tickMarks: Int = 0
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
setup()
}
override func prepareForInterfaceBuilder() {
setup()
}
override func awakeFromNib() {
setup()
}
private func setup() {
let stack = NSStackView()
stack.orientation = .horizontal
stack.translatesAutoresizingMaskIntoConstraints = false
stack.addArrangedSubview(sliderLabel)
stack.addArrangedSubview(slider)
stack.addArrangedSubview(valueLabel)
stack.addArrangedSubview(enabledCheckbox)
sliderLabel.stringValue = label
slider.doubleValue = value
valueLabel.stringValue = valueFormatter(value)
slider.minValue = minimum
slider.maxValue = maximum
slider.numberOfTickMarks = tickMarks
// Make the slider be the one that expands to fill available space
slider.setContentHuggingPriority(NSLayoutConstraint.Priority(rawValue: 249), for: .horizontal)
sliderLabel.widthAnchor.constraint(equalToConstant: 60).isActive = true
valueLabel.widthAnchor.constraint(equalToConstant: 60).isActive = true
addSubview(stack)
stack.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
stack.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
stack.topAnchor.constraint(equalTo: topAnchor).isActive = true
stack.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
#objc func sliderChanged(_ sender: Any) {
guard let slider = sender as? NSSlider else { return }
valueLabel.stringValue = valueFormatter(slider.doubleValue)
print("Slider now: \(slider.doubleValue)")
delegate?.adjustable(self, changedValue: slider.doubleValue)
}
#objc func enabledChanged(_ sender: Any) {
guard let checkbox = sender as? NSButton else { return }
print("Enabled now: \(checkbox.state == .on)")
delegate?.adjustable(self, changedEnabled: checkbox.state == .on)
}
}
The solution, as described in the question linked by Willeke, was to ensure init had completed before referencing self. (I'm slightly surprised the compiler allowed it to be used in a property initialiser)
Wrong:
private let slider = NSSlider(target: self, action: #selector(sliderChanged(_:)))
private let enabledCheckbox = NSButton(checkboxWithTitle: "Enabled", target: self, action: #selector(enabledChanged(_:)))
Right:
private lazy var slider = NSSlider(target: self, action: #selector(sliderChanged(_:)))
private lazy var enabledCheckbox = NSButton(checkboxWithTitle: "Enabled", target: self, action: #selector(enabledChanged(_:)))
import UIKit
extension UIView {
func toImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func sendPrint(sender: AnyObject) {
let testView = UIView(frame: CGRectMake(0, 0, 200, 200))
testView.backgroundColor = UIColor.blueColor()
let printcontroller = UIPrintInteractionController.sharedPrintController()
let printinfo = UIPrintInfo(dictionary:nil)
printinfo.jobName = "Printing an Image"
printinfo.outputType = UIPrintInfoOutputType.General
printcontroller.printInfo = printinfo
// printcontroller.printFormatter = webView.viewPrintFormatter()
printcontroller.showsNumberOfCopies = false
printcontroller.presentAnimated(true) { (_, isPrinted, error) in
if error == nil
{
if isPrinted
{
print ("Printed Successfully")
} else
{
print ("Printing failed")
}
}
}
}
}
I have written this code to AirPrint the UserInterface of of my View.
But now code is not working anymore.
I am getting runtime error : "attempting to display print options with no printing source (item/items/formatter/renderer) set"
Please help me, I am stuck in this code for the last 3 days.
I just want to generate the image from the UIView, which contains 2 or 3 labels and an image.