swift - 对拖动视图做出反应
问题描述
我有一个视图,只要在它上面发生长按或拖动,我就想改变它。它可以在视图之外开始,也可以在内部开始。
struct ContentView: View {
@State var active: Bool = false
var body: some View {
Rectangle()
.fill(self.active ? Color.red : Color.secondary)
}
}
这种行为的一个例子是 iPhone 键盘:当您长按某个键时,它会弹出 ( active = true
)。当您移出它时,它会弹出 ( active = false
) 但下一个键随后处于活动状态。
我尝试过使用LongPressGesture
,但无法弄清楚如何让它按我想要的方式运行。
解决方案
我在操场上为你做了例子来展示如何使用LongPressGestureRecognizer
.
您将手势识别器添加到您想要长按的视图中,target
作为处理手势识别的父控制器(ContentView
在您的情况下)并且action
长按会发生什么。
在我的实现中,长按视图bodyView
会将其颜色从透明变为红色。这发生在didSet
属性内部showBody
,它调用showBodyToggled()
. 我正在检查state
手势,因为手势识别器将为每个状态发送消息(我只在状态为 时执行操作.began
)。
如果您有任何问题,请告诉我:
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
var bodyView: UIView!
var showBody = false {
didSet {
showBodyToggled()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureSubviews()
configureLongPressRecognizer()
}
func configureSubviews() {
bodyView = UIView()
bodyView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bodyView)
NSLayoutConstraint.activate([
bodyView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
bodyView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
bodyView.heightAnchor.constraint(equalToConstant: 200),
bodyView.widthAnchor.constraint(equalToConstant: 300)
])
}
func configureLongPressRecognizer() {
bodyView.addGestureRecognizer(
UILongPressGestureRecognizer(
target: self,
action: #selector(longPressed(_:))
)
)
}
@objc func longPressed(_ sender: UILongPressGestureRecognizer) {
// the way I'm doing it: only acts when the long press first happens.
// delete this state check if you'd prefer the default long press implementation
switch sender.state {
case .began:
showBody = !showBody
default:
break
}
}
func showBodyToggled() {
UIView.animate(withDuration: 0.4) { [weak self] in
guard let self = self else { return }
self.bodyView.backgroundColor = self.showBody ? .red : .clear
}
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
编辑:
这是 SwiftUI 中的一个示例,其中长按 0.5 秒可在红色和黑色之间切换圆圈的颜色
struct ContentView: View {
@State var active = false
var longPress: some Gesture {
LongPressGesture()
.onEnded { _ in
withAnimation(.easeIn(duration: 0.4)) {
self.active = !self.active
}
}
}
var body: some View {
Circle()
.fill(self.active ? Color.red : Color.black)
.frame(width: 100, height: 100, alignment: .center)
.gesture(longPress)
}
}
推荐阅读
- automation - UI Automator 查看器错误:获取设备屏幕截图时出错:EOF 获取设备屏幕截图时出错:EOF
- python - 如何读取多个 csv 文件?
- java - 如果数据库中表的 ans 列为空,我想给出“编辑链接,即编辑”
- javascript - 如何在 React Native 中使用自定义警报?
- java - 如何使用 getter 和 setter 获取用户输入
- android - 为什么调用活动的 onActivityResult() 在被调用活动的 onCreate() 之前执行?
- c - 如何将 CSV 文件读入二维结构数组,每个元素都有一个确定字符(C、G、M)以排序到结构中?
- laravel - 并发连接 Apache 和 Laravel
- python - 带有 flow_from_directory val_acc 的 Keras VGG16 没有上升
- python - 读取最后打印的行并使用“if”语句将其删除