首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >怎么用手指移动线?

怎么用手指移动线?
EN

Stack Overflow用户
提问于 2017-08-26 12:05:54
回答 1查看 606关注 0票数 0

我在ViewController中为一行定义了以下变量。

代码语言:javascript
复制
var scanlineRect = CGRect.zero
var scanlineStartY: CGFloat = 0
var scanlineStopY: CGFloat = 0
var topBottomMargin: CGFloat = 30
var scanLine: UIView = UIView()

我可以用UIView画一条线,也可以用UIView.animate方法向垂直方向移动。如何移动一条用手指拖动的线?

代码语言:javascript
复制
func drawLine() 
{
    self.view.addSubview(scanLine)
    scanLine.backgroundColor = UIColor.black
    scanlineRect = CGRect(x: 15, y: 0, width: self.view.frame.width - 30, height: 5)
    scanlineStartY = topBottomMargin
    scanlineStopY = self.view.frame.height - topBottomMargin
    scanLine.frame  = scanlineRect
    scanLine.center = CGPoint(x: scanLine.center.x, y: scanlineStartY)
    scanLine.isHidden = false
}
func Move(Location : CGPoint) 
{
    scanLine.isHidden = false
    weak var weakSelf = scanLine
    UIView.animate(withDuration: 3.0, animations: {
        weakSelf!.center = CGPoint(x: weakSelf!.center.x, y: Location.y)
    }, completion: nil)

}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
{    
    var lastPoint = CGPoint.zero
    if let touch = touches.first
    {
        lastPoint = touch.location(in: self.view)
    }
    Move(Location: lastPoint)
}

override func viewDidLoad() 
{
    super.viewDidLoad()
    drawLine()
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-26 14:15:48

尝试使用touchesMoved而不是touchesBegan

代码语言:javascript
复制
 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    guard let location = touch?.location(in: self.view) else{
        return
    }
    scanLine.frame.origin = CGPoint(x: location.x-scanLine.frame.size.width/2, y: location.y-scanLine.frame.size.height/2)
}

已更新

如果只想在y轴中移动,只需在中移动,则需要更改这一行。

代码语言:javascript
复制
scanLine.frame.origin = CGPoint(x: location.x-scanLine.frame.size.width/2, y: location.y-scanLine.frame.size.height/2)

使用这个代替,注意scanline.frame.origin.x没有变化

代码语言:javascript
复制
scanLine.frame.origin = CGPoint(x: scanLine.frame.origin.x, y: location.y-scanLine.frame.size.height/2)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45895160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档