对于iOS 10.0+,您可以尝试UIFeedbackGenerator
上面的简单viewController,只需在测试“单视图应用”中替换您的视图控制器
import UIKit
class ViewController: UIViewController {
var i = 0
override func viewDidLoad() {
super.viewDidLoad()
let btn = UIButton()
self.view.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.widthAnchor.constraint(equalToConstant: 160).isActive = true
btn.heightAnchor.constraint(equalToConstant: 160).isActive = true
btn.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
btn.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
btn.setTitle("Tap me!", for: .normal)
btn.setTitleColor(UIColor.red, for: .normal)
btn.addTarget(self, action: #selector(tapped), for: .touchUpInside)
}
@objc func tapped() {
i += 1
print("Running \(i)")
switch i {
case 1:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.error)
case 2:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.success)
case 3:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.warning)
case 4:
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()
case 5:
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
case 6:
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
default:
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
i = 0
}
}
}