2016-04-16 9 views
0

iOSの画面にジェスチャーが認識された場所を描くためのこのチュートリアルでは、描画された図形にテキストラベルを追加する

https://www.weheartswift.com/bezier-paths-gesture-recognizers/

私は今、機能を拡張したいとそれらの座標を示す私の新しく描かれた図形にテキストラベルを追加したいのです。

だから、画面に触れると矩形が描かれますが、これはパンのジェスチャーで動いていますが(これまでのところ良いですが)、座標を示す数字も表示したいと思います。

これを行うにはどうしたらよいですか?

単に、座標の文字列を作成 NSStringにそれをキャストしてから drawAtPointメソッドを呼び出します
("\(frame.origin.x), \(frame.origin.y)" as NSString).drawAtPoint(.zero, withAttributes: [ 
    NSFontAttributeName: UIFont.systemFontOfSize(14), 
    NSForegroundColorAttributeName: UIColor.blackColor() 
    ]) 

:あなたのような何かをビューの座標を描くことができ、あなたのdrawRect実装で

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

ビューのコンテキストで描画します。

もちろん、.zeroを任意のCGPointに変更することができます。これは、文字列を描画する場所によって異なります。また、必要に応じて属性を編集することもできます。

は、これはあなたの周りのユーザーパンも追加したいいつ更新されることを確認します:

self.setNeedsDisplay() 

をごdidPan方法の底に。

希望するもの:

+0

これは大いに役立ちます、ありがとうございます。私はパンでそれを更新する方法を尋ねようとしていました、そして、あなたは感情的に答えているのを見ました! :) – sova