我使用以下代码绘制线条。线条边缘有点,我想在用户点击结束点时显示工具提示。 代码段在下面,
override func drawRect(rect: CGRect) {
// Drawing code
UIColor.brownColor().set()
let context = UIGraphicsGetCurrentContext()
//CGContextSetLineWidth(context, 5)
CGContextMoveToPoint(context, 50, 50)
CGContextAddLineToPoint(context,100, 200)
CGContextStrokePath(context)
// now add the circle on at the line edges
var point = CGPoint(x:50 , y:50)
point.x -= 5.0/2
point.y -= 5.0/2
var circle = UIBezierPath(ovalInRect: CGRect(origin: point, size: CGSize(width: 5.0,height: 5.0)))
circle.fill()
point = CGPoint(x:100 , y:200)
point.x -= 5.0/2
point.y -= 5.0/2
circle = UIBezierPath(ovalInRect: CGRect(origin: point, size: CGSize(width: 5.0,height: 5.0)))
circle.fill()
}
有没有人知道如何识别这个特定的点被点击,以及我将如何显示工具提示。 我正在寻找一个快速的解决方案。
答案 0 :(得分:1)
定义一个结构来保存你必须触摸的点,以及要显示的文本:
struct TouchPoint {
var point: CGPoint // touch near here to show a tooltip
var tip: String // show this text when touched
}
然后在你定义UIView
的{{1}}子类中,在某处保留它们:
drawRect
var touchPoints: [TouchPoint] = [] // where we have to touch and what tooltip to show
可以多次调用,所以每次都要重新开始:
drawRect
您需要检测UIView上的点击,因此通过更改其初始化来添加手势识别器:
override func drawRect(rect: CGRect) {
touchPoints = []
// ...
// add a touchPoint for every place to touch
touchPoints.append(TouchPoint(point: point, tip: "point 1"))
}
然后你需要一种方法来查看触摸是否接近接触点,并显示正确的工具提示:
required init?(coder aDecoder: NSCoder) {
// standard init for a UIView wiht an added gesture recognizer
super.init(coder: aDecoder)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("touched:")))
}
并偶然使用新版本的func touched(sender:AnyObject) {
let tapTolerance = CGFloat(20) // how close to the point to touch to see tooltip
let tipOffset = CGVector(dx: 10, dy: -10) // tooltip offset from point
let myTag = 1234 // random number not used elsewhere
guard let tap:CGPoint = (sender as? UITapGestureRecognizer)?.locationInView(self) else { print("touched: failed to find tap"); return }
for v in subviews where v.tag == myTag { v.removeFromSuperview() } // remove existing tooltips
let hitPoints:[TouchPoint] = touchPoints.filter({CGPointDistance($0.point, to: tap) < tapTolerance}) // list of tooltips near to tap
for h in hitPoints { // for each tooltip to show
let f = CGRect(origin: h.point+tipOffset, size: CGSize(width: 100, height: 20)) // fixed size label :-(
let l = UILabel(frame: f)
l.tag = myTag // just to be able to remove the tooltip later
l.text = h.tip // draw the text
addSubview(l) // add the label to the view
}
}
func CGPointDistanceSquared(from: CGPoint, to: CGPoint) -> CGFloat { return (from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y) }
func CGPointDistance(from: CGPoint, to: CGPoint) -> CGFloat { return sqrt(CGPointDistanceSquared(from, to: to)) }
运算符在+
上执行向量添加:
CGPoint
这对我来说没问题。额外的调整是从文本字符串计算UILabel大小,并移动UILabel使其不会从边缘的UIView侧面运行。祝你好运!