我正在尝试设计一个界面,在该界面上,点击可以淡入文本,然后淡出文本,但是在屏幕上向上拖动两个手指可以使其变亮,而向下拖动两个手指可以使屏幕变暗。我已经使文本淡入和淡出,但是我似乎无法使亮度功能正常工作。该应用程序正在构建中,但是两根手指的手势根本不起作用。
我尝试插入发现的here代码。
我尝试了Stack Overflow上发现的其他几种方法,例如也发现了here,但没有运气。
更新:我根据@rmaddy和@ leo-dabus的反馈意见进行了一些更改。当我在模拟器或iPhone上平移时,仍然什么也没有发生。我不确定是否应该使用“ recognizer.state”而不是“ sender.state”。我确定我会犯很多新手错误。我什至在正确的位置上有平移手势的代码吗?这是我现在拥有的:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Hide text on launch
self.text.alpha = 0
}
// Introducing: The text!
@IBOutlet weak var text: UITextView!
// Show text upon tap of gesture recognizer
@IBAction func tap(_ sender: UITapGestureRecognizer) {
// fade in
UIView.animate(withDuration: 0.5, animations: {
self.text.alpha = 1.0
}) { (finished) in
// fade out
UIView.animate(withDuration: 4.0, animations: {
self.text.alpha = 0.0
})
}
}
@IBAction func twoFingerPan(_ sender: UIPanGestureRecognizer) {
if sender.state == UIPanGestureRecognizer.State.changed || sender.state == UIPanGestureRecognizer.State.ended {
let velocity:CGPoint = sender.velocity(in: self.view)
if velocity.y > 0 {
UIScreen.main.brightness -= 0.03
}
else {
UIScreen.main.brightness += 0.03
}
}
}
}
答案 0 :(得分:0)
我建议创建几个手势识别器。像这样:
fileprivate func setGestureRecognizers() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
tapGesture.delegate = self as? UIGestureRecognizerDelegate
tapGesture.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGesture)
let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(twoFingerPan(_:)))
panGesture.delegate = self as? UIGestureRecognizerDelegate
panGesture.minimumNumberOfTouches = 1
view.addGestureRecognizer(panGesture)
}
在viewDidLoad上调用此方法:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Hide text on launch
self.text.alpha = 0
setGestureRecognizers()
}
然后,我更改了一些方法,因为我使用代码而不是使用故事板设置了手势识别器,因此我摆脱了@IBAction
并添加了@objc
。另外,我也在手机上进行了测试,并比较了velocity.y > 0
的手势对手指的移动过于敏感,因此将其更改为0.4
。
// Show text upon tap of gesture recognizer
@objc func tap(_ sender: UITapGestureRecognizer) {
// fade in
UIView.animate(withDuration: 0.5, animations: {
self.text.alpha = 1.0
}) { (finished) in
// fade out
UIView.animate(withDuration: 4.0, animations: {
self.text.alpha = 0.0
})
}
}
@objc func twoFingerPan(_ sender: UIPanGestureRecognizer) {
if sender.state == UIPanGestureRecognizer.State.changed || sender.state == UIPanGestureRecognizer.State.ended {
let velocity:CGPoint = sender.velocity(in: self.view)
if velocity.y > 0.4 {
UIScreen.main.brightness -= CGFloat(0.03)
}
else {
UIScreen.main.brightness += CGFloat(0.03)
}
}
}