Reputation: 5660
I'm following along with this tutorial for drawing squares where-ever there is a gesture recognized touch on the screen in iOS.
https://www.weheartswift.com/bezier-paths-gesture-recognizers/
I am now wanting to extend the functionality and want to add text labels to my newly drawn shapes indicating their coordinates.
So touching the screen would draw a rectangle, which moves with the pan gesture (so far so good) but I would also like it to show numbers indicating the coordinates.
How can I go about accomplishing this?
class CircularKeyView: UIView {
// a lot of this code came from https://www.weheartswift.com/bezier-paths-gesture-recognizers/
//all thanks goes to we<3swift
let lineWidth: CGFloat = 1.0
let size: CGFloat = 44.0
init(origin: CGPoint) {
super.init(frame: CGRectMake(0.0, 0.0, size, size))
self.center = origin
self.backgroundColor = UIColor.clearColor()
initGestureRecognizers() //start up all the gesture recognizers
}
func initGestureRecognizers() {
let panGR = UIPanGestureRecognizer(target: self, action: "didPan:")
addGestureRecognizer(panGR)
}
//PAN IT LIKE u FRYIN.
func didPan(panGR: UIPanGestureRecognizer) {
self.superview!.bringSubviewToFront(self)
var translation = panGR.translationInView(self)
self.center.x += translation.x
self.center.y += translation.y
panGR.setTranslation(CGPointZero, inView: self)
}
// We need to implement init(coder) to avoid compilation errors
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let path = UIBezierPath(roundedRect: rect, cornerRadius: 7)
//draws awesome curvy rectangle
UIColor.darkGrayColor().setFill()
path.fill()
//draws outline
path.lineWidth = self.lineWidth
UIColor.blackColor().setStroke()
path.stroke()
//////
//probably where I should draw the text label on this thing,
//although it needs to update when the thingy moves.
}
}
Upvotes: 1
Views: 758
Reputation: 4905
In your drawRect
implementation you can draw the coordinates of the view with something like:
("\(frame.origin.x), \(frame.origin.y)" as NSString).drawAtPoint(.zero, withAttributes: [
NSFontAttributeName: UIFont.systemFontOfSize(14),
NSForegroundColorAttributeName: UIColor.blackColor()
])
Which simply creates a string of the coordinates, casts it to an NSString
and then calls the drawAtPoint
method to draw it in the view's context.
You can of course change .zero
to any CGPoint
depending on where you want to draw the string and can edit the attributes as desired.
To make sure that this gets updated when the user pans around you will want to also add:
self.setNeedsDisplay()
to the bottom of your didPan
method.
Hope this helps :)
Upvotes: 1