![](/img/trans.png)
[英]How can I track a CGPoint of a touch input in a UIView, as the finger moves along the view?
[英]How can I create a UIView at a certain CGPoint?
我需要能夠在某個 CGPoint 上創建和顯示 UIView。
到目前為止,我有一個作為子視圖添加到主視圖的手勢識別器。
然后我以編程方式創建一個 UIView 並將它的 x 和 y 坐標設置為我從手勢識別器獲得的 CGPoint。
我能夠創建它並將其添加為子視圖,但創建的 UIView 的位置與 TAP 的位置不同。
AnimationView 子類 UIView
我的代碼在下面
tappedLocation = gesture.locationInView(self.view)
var animationImage: AnimationView = AnimationView()
animationImage.frame = CGRectMake(tappedLocation.x, tappedLocation.y, 64, 64)
animationImage.contentMode = UIViewContentMode.ScaleAspectFill
self.view.addSubview(animationImage)
animationImage.addFadeAnimation(removedOnCompletion: true)
有什么我做錯了嗎?
您的問題是,您希望視圖的中心是您單擊的點。 此時UIView
左上角將是您觸摸的點。 所以試試吧:
var frameSize:CGFloat = 64
animationImage.frame = CGRectMake(tappedLocation.x - frameSize/2, tappedLocation.y - frameSize/2, frameSize, frameSize)
如您所見,現在您之前設置寬度和高度並調整 x 和 y,以便您的視圖中心是您觸摸的點。
但更好的方法是,就像 Rob 在他的回答中提到的那樣,將視圖的中心設置為您的位置。 這樣,您只需設置框架的大小並使用CGSizeMake
代替CGRectMake
方法:
animationImage.frame.size = CGSizeMake(100, 100)
animationImage.center = tappedLocation
只需設置其center
:
animationImage.center = tappedLocation
讓我們創建一個點擊手勢並將其分配給一個視圖
let tapGesture = UITapGestureRecognizer()
tapGesture.addTarget(self, action: "tappedView:") // action is the call to the function that will be executed every time a Tap gesture gets recognised.
let myView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
myView.addGestureRecognizer(tapGesture)
每次您使用指定的點擊手勢點擊視圖時,都會調用此函數。
func tappedView(sender: UITapGestureRecognizer) {
// Now you ca access all the UITapGestureRecognizer API and play with it however you want.
// You want to center your view to the location of the Tap.
myView.center = sender.view!.center
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.