定義一個struct抱着你必須觸摸點,以及文字顯示:
struct TouchPoint {
var point: CGPoint // touch near here to show a tooltip
var tip: String // show this text when touched
}
然後在UIView
子類中,可以定義drawRect
,使地方,讓他們:
var touchPoints: [TouchPoint] = [] // where we have to touch and what tooltip to show
drawRect
可以多次調用,所以每次都重新開始:
override func drawRect(rect: CGRect) {
touchPoints = []
// ...
// add a touchPoint for every place to touch
touchPoints.append(TouchPoint(point: point, tip: "point 1"))
}
您需要檢測水龍頭上的UIView,因此通過改變它的初始化添加一個手勢識別:
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
向量加法:
func +(left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x+right.dx, y: left.y+right.dy) }
這對我來說可行。額外的調整將是從文本字符串中計算UILabel大小,並移動UILabel,使其不會在UIView的邊緣處運行。祝你好運!
我很感謝你的回答,但我意識到管理標籤以及設備方向的變化非常困難,所以我採取了一種稍微不同的方法來完成這項任務。在我繪製圓圈的最終點,我將它們作爲按鈕,在按鈕上有一個點圖像。然後在按鈕上單擊我顯示縮小大小popover並顯示工具提示。它對我來說是完美的,但我很欣賞你的努力。 – neena
我發現這是一個有趣的問題,我擴展了這段代碼以便像彈出框一樣在框中繪製框,並自動調整框的大小並將其移動,以使它不會與繪圖邊界附近的邊緣或接觸點重疊。但是你的想法聽起來也不錯。謝謝你的勾號! – emrys57