【问题标题】:How to move line with finger?如何用手指移动线?
【发布时间】:2017-08-26 12:05:54
【问题描述】:

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

var scanlineRect = CGRect.zero
var scanlineStartY: CGFloat = 0
var scanlineStopY: CGFloat = 0
var topBottomMargin: CGFloat = 30
var scanLine: UIView = UIView()

我可以使用 UIView 绘制一条线,并可以使用 UIView.animate 方法将其沿垂直方向移动。如何用手指拖动一条线?

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()
}

【问题讨论】:

  • 仅供参考 - 与您的问题无关,但不要在您的 Move 方法中强制解开 weakSelf。正确解包,因为它可能是 nil 并导致您的应用崩溃。
  • 你只是在问如何拖动视图???
  • 顺便说一句,与 Xcode 或 Core Graphics 无关。
  • @rmaddy 如何正确解包并避免应用崩溃?
  • 解开它就像你做任何其他可选的。

标签: ios swift swift3 core-graphics


【解决方案1】:

尝试使用touchesMoved 而不是touchesBegan

 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轴上移动你需要改变这条线

scanLine.frame.origin = CGPoint(x: location.x-scanLine.frame.size.width/2, y: location.y-scanLine.frame.size.height/2)

改用这个注意scanline.frame.origin.x没有改变

scanLine.frame.origin = CGPoint(x: scanLine.frame.origin.x, y: location.y-scanLine.frame.size.height/2)

【讨论】:

  • 我无法编译。我有以下错误: ViewController 类型的值没有成员“superview”。 ViewController 类型的值没有成员“框架”
  • 您为什么要更改 OP 在其 touchesBegan 方法中的所有好代码并用糟糕的 Swift 代码替换它只是为了说 touchesBegan 应该更改为 touchesMoved?这是 Swift,不要使用分号。这是一个视图控制器,使用self.view,而不是self.superview。在 Swift 中,不要根据 nil 检查变量,如果不是则强制解包。相反,安全地解包变量,就像在 OP 的原始代码中一样。
  • @rmaddy 这是一个旧代码,我没有经常审查它,是我的错误,现在我已经更新了我的答案,请你告诉我它是否是一个错误的代码?我一直很感激你的 cmets,最好的问候
  • @ReinierMelian 我检查了你的答案。没关系,但是如何禁用右/左移动?我只需要上下移动。
  • @Vladislav 再次检查我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多