How to add interactive UILabels on top of UIImageView?

I need to add some labels on top of the UIImageView . Label text can be changed by clicking on them. What is the best way to achieve this? I use the Swift programming language. Having raised some of the solutions in stackoverflow, I found a couple of hikes that use the String.drawInRect method to draw some text in a rectangle, which is then placed in a UIImageView . But, like me, I don’t think I can change the text or even recognize the touch event. Please, help.

UPDATE

My code is:

 override func viewDidLoad() { super.viewDidLoad() let img = UIImage(named: "Image") let imgView = UIImageView(image: img) self.view.addSubview(imgView) var myLabel = UILabel() myLabel.text = "Hello There" myLabel.textColor = UIColor.redColor() myLabel.font = UIFont(name: "Marker Felt", size: 20) myLabel.accessibilityIdentifier = "this is good!" myLabel.frame = CGRect(x: img!.size.width/2 /* - myLable.width / 2 ? */, y: 0, width: img!.size.width, height: 40) imgView.addSubview(myLabel) imgView.userInteractionEnabled = true myLabel.userInteractionEnabled = true let tapGesture = UITapGestureRecognizer(target: self, action: "handlePanGesture:") myLabel.addGestureRecognizer(tapGesture) } func handlePanGesture(sender: UITapGestureRecognizer) { var senderView = sender.view as! UILabel print(senderView.text) senderView.text = "look how i changed!" print(senderView.accessibilityIdentifier) } 

While the results are positive, I have an image with an inscription on top of it that can respond to touch events. Now I need to find the width of the label so that I can efficiently center it when necessary. Then I need to find a way to place the labels at the exact coordinate relative to the upper left corner of the image as a source.

Any help in these two tasks would be greatly appreciated.

+6
source share
8 answers

Adding a label to ImageView is the best approach. but you can also do this by adding a button to the ImageView .

I created an example in which I created an ImageView on a storyboard and created its output in the ViewController class, and in viewDidLoad I created a label, added it to the label, and added the UITapGestureRecognizer to the label. when the user clicks on the label, we change the text of the label and its position.

 class ViewController: UIViewController { @IBOutlet weak var winterImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() let label = UILabel(frame: CGRect(x: 10, y: 0, width: self.winterImageView.frame.width - 10, height: 30)) label.textColor = UIColor.redColor() label.userInteractionEnabled = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:))) label.addGestureRecognizer(tapGesture) label.text = "Is Winter is coming, My Friend?" self.winterImageView.addSubview(label) } 

enter image description here

Change label text and position in handleTap

  /// handle tap here func handleTap(sender: UITapGestureRecognizer) { let senderView = sender.view as! UILabel senderView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: senderView, attribute: .CenterX, relatedBy: .Equal, toItem: self.winterImageView, attribute: .CenterX, multiplier: 1, constant: 0).active = true NSLayoutConstraint(item: senderView, attribute: .CenterY, relatedBy: .Equal, toItem: self.winterImageView, attribute: .CenterY, multiplier: 1, constant: 0).active = true print(senderView.text) senderView.text = "Yes!!! Winter is coming, My Friend!!" } 

enter image description here

You can download the project from here InteractiveLabel

+6
source

I can see from other answers and comments related to each other almost the same. If you are familiar with Cocoa pods, then you will agree with my opinion. Always look at yourself and choose the best. If you want your project to go smoothly and steadily, then JLStickerTextView is your friend and his way to go. This is a free, elegant and brighter shortcut customization project, accessible to everyone, and the best in this project is written in a convenient form of Swift .

Github Link : https://github.com/luiyezheng/JLStickerTextView

Functions

  • You can add multiple files at once to StickerTextView.
  • Multi line support.
  • Rotate, resize text with one finger.
  • Set color, alpha, font, alignment, TextShadow, lineSpacing ...... text
  • StickerTextView also handles the process of rendering text in Image Written in Swift

Note: In, My personal opinion. Look, the code was written in these projects is simply excellent and correctly classified.

Link to attribute attributes:

enter image description here

MainView Screenshot from the project:

enter image description here

The conclusion from my personal project based on JLStickerTextView.I, I hope you will consider it. If you need more information, let me know ...

enter image description here

+2
source

github.com/khush004/StickerView/tree/master

here is the JLStickerTextView code, which is error free compatible with swift 3.0

+2
source

You can use the label and add a gesture recognizer from which you can set the action.

EDIT (response to OP comment):

Basically, you put a UILabel on top of your card, install a gesture recognizer on it and set the hidden UITextField in the same position as your label. Thus, when you click on it, you indicate in your gesture recognition method that the user interface should indicate the label as hidden and the text field as visible. When you are done (editing), just save the changes and refresh the user interface.

+1
source

If you just want to center the alignment of UILabel and UIImageView, you can use the AutoLayout constraint.

 NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: imageView, attribute: .CenterX, multiplier: 1, constant: 0).active = true NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: imageView, attribute: .CenterY, multiplier: 1, constant: 0).active = true 
+1
source
 func handlePanGesture(sender: UITapGestureRecognizer) { let senderView = sender.view as! UILabel print(senderView.text) senderView.textColor = UIColor.redColor() senderView.text = "look how i changed!" print(senderView.accessibilityIdentifier) } 

Output:

sender.view? .frame

β–Ώ Optional β–Ώ Some: CGRect β–Ώ Origin: CGPoint - x: 0,0 - y: 0.0 {...} β–Ώ Size: CGSize - Width: 335.0 - Height: 28.0

+1
source

I use CALayers, gesture recognizers and the hitTest method for layers. Sample code below:

 class ImageView: UIImageView { let tapGesture = UITapGestureRecognizer() let redLayer = CATextLayer() var redHitCounter:Int = 0 let greenLayer = CATextLayer() var greenHitCounter:Int = 0 override init(frame: CGRect) { super.init(frame: frame) setUpClickableLayers() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpClickableLayers() } private func setUpClickableLayers() { self.isUserInteractionEnabled = true tapGesture.numberOfTapsRequired = 1 tapGesture.addTarget(self, action: #selector(changeText)) self.addGestureRecognizer(tapGesture) redLayer.frame = CGRect(x: 40, y: 40, width: 100, height: 40) redLayer.backgroundColor = UIColor.red.cgColor redLayer.string = String(redHitCounter) redLayer.alignmentMode = kCAAlignmentCenter self.layer.addSublayer(redLayer) greenLayer.frame = CGRect(x: 40, y: 140, width: 100, height: 40) greenLayer.backgroundColor = UIColor.green.cgColor greenLayer.string = String(redHitCounter) greenLayer.alignmentMode = kCAAlignmentCenter self.layer.addSublayer(greenLayer) } internal func changeText(_ recognizer:UITapGestureRecognizer) { let p = recognizer.location(in: self) if (redLayer.hitTest(p) != nil) { redHitCounter += 1 redLayer.string = String(redHitCounter) } else if (greenLayer.hitTest(p) != nil) { greenHitCounter += 1 greenLayer.string = String(greenHitCounter) } } } 

A few notes:

(1) Remember to set UIImageView isUserInteractionEnabled to true. It took me an hour to debug why my UIImageView saw gestures!

(2) The hitTest () method works for CALayer and all subclasses. Remember to make the layer large enough to work on thick fingers.

(3) You can also use pan and pinch gestures to move, rotate and resize the target layer.

+1
source

if anyone comes across this post for SWIFT 4, here is the updated module:

module "JLStickerTextView",: git => " https://github.com/dannn5n2/JLStickerTextView.git "

I converted it to Swift 4 everything works! ENJOY!!

0
source

Source: https://habr.com/ru/post/1257637/


All Articles