2016-04-16 48 views
0

我正在跟隨本教程繪製正方形,其中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

如果你想要點擊手勢,那麼你爲什麼要使用平移手勢? –

+0

@ShubhamOjha理想情況下,座標標籤/文本將更新關於這些東西的移動。 – sova

回答

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方法的底部。

希望這有助於:)

+0

這非常有幫助,謝謝。我正要問如何在平臺上更新它,並且看到你已經預感到了迴應! :) – sova