菜鸟教程小白 发表于 2022-12-12 23:33:17

ios在 View 中添加panGesture,更改 View 框架,但不流畅


                                            <p><p> <img src="/image/Jffjb.gif" alt="enter image description here"/> </p>

<p>我给<code>self.view</code>加了一个view,给view加了一个<code>UIPangestureRecognizer</code>, move view,但是不流畅,感觉不流畅,
这是我的代码,谢谢你帮助我</p>

<pre><code>var redView:UIView = UIView();
var redFrame:CGRect = CGRect();
override func viewDidLoad() {
    super.viewDidLoad()
    redView = UIView.init(frame: CGRect.init(x: 0, y: 100, width: KWidth, height: 40))
    redView.backgroundColor = UIColor.red
    self.redFrame = redView.frame;
    self.view.addSubview(redView);
    let pan:UIPanGestureRecognizer = UIPanGestureRecognizer.init(target: self, action: #selector(moveFunction(pan:)))
    self.redView.addGestureRecognizer(pan)
}
func moveFunction(pan:UIPanGestureRecognizer) {
    let point:CGPoint = pan.translation(in: self.view)
    pan.setTranslation(CGPoint.zero, in: self.view)
    ifpan.state == .changed{
      print(point)
      let redY:CGFloat = redView.frame.origin.y + point.y
      redView.frame = CGRect.init(x: 0, y: Int(redY), width: KWidth, height: 40)
    }
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>可能此代码对您有所帮助。我正在使用平移手势更改 View(panView) 高度约束。</p>

<pre><code>@IBOutlet weak var h: NSLayoutConstraint!
@IBOutlet weak var panView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    let gesture = UIPanGestureRecognizer(target: self, action: #selector(self.pan(_:)))
    panView.addGestureRecognizer(gesture)
}

@objc func pan(_ pan: UIPanGestureRecognizer) {

    let translation = pan.translation(in: panView)

    if pan.state == .began {
    } else if pan.state == .changed {
      h.constant = h.constant - translation.y
      pan.setTranslation(CGPoint.zero, in: panView)
    } else if pan.state == .ended {
      // You can handle this how you want.
    }
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios在 View 中添加panGesture,更改 View 框架,但不流畅,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41479393/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41479393/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios在 View 中添加panGesture,更改 View 框架,但不流畅