我正在按照本教程绘制正方形 - 在iOS中屏幕上有一个手势识别触摸。
https://www.weheartswift.com/bezier-paths-gesture-recognizers/
我现在想要扩展功能,并希望为我新绘制的形状添加文本标签,以指示它们的坐标。
因此触摸屏幕会绘制一个矩形,随着平移手势移动(到目前为止一直很好),但我还希望它显示指示坐标的数字。
我怎样才能完成这项工作?
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.
}
}
答案 0 :(得分:1)
在drawRect
实现中,您可以使用以下内容绘制视图的坐标:
("\(frame.origin.x), \(frame.origin.y)" as NSString).drawAtPoint(.zero, withAttributes: [
NSFontAttributeName: UIFont.systemFontOfSize(14),
NSForegroundColorAttributeName: UIColor.blackColor()
])
只需创建一个坐标字符串,将其强制转换为NSString
,然后调用drawAtPoint
方法在视图的上下文中绘制它。
您当然可以将.zero
更改为任何CGPoint
,具体取决于您想要绘制字符串的位置,并可以根据需要编辑属性。
要确保在用户平移时更新此内容,您还需要添加:
self.setNeedsDisplay()
到didPan
方法的底部。
希望这会有所帮助:)