Example shows how to trigger an impact haptic using UIImpactFeedbackGenerator
after a button press.
class ViewController: UIViewController
{
lazy var button: UIButton =
{
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(button)
button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
button.setTitle("Impact", for: .normal)
button.setTitleColor(UIColor.gray, for: .normal)
return button
}()
// Choose between heavy, medium, and light for style
let impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .heavy)
override func viewDidLoad()
{
super.viewDidLoad()
button.addTarget(self, action: #selector(self.didPressButton(sender:)), for: .touchUpInside)
// Primes feedback generator for upcoming events and reduces latency
impactFeedbackGenerator.prepare()
}
func didPressButton(sender: UIButton)
{
// Triggers haptic
impactFeedbackGenerator.impactOccurred()
}
}
@interface ViewController ()
@property (nonatomic, strong) UIImpactFeedbackGenerator *impactFeedbackGenerator;
@property (nonatomic, strong) UIButton *button;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.button addTarget:self action:@selector(didPressButton:) forControlEvents:UIControlEventTouchUpInside];
// Choose between heavy, medium, and light for style
self.impactFeedbackGenerator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleHeavy];
// Primes feedback generator for upcoming events and reduces latency
[self.impactFeedbackGenerator prepare];
}
- (void)didPressButton:(UIButton *)sender
{
// Triggers haptic
[self.impactFeedbackGenerator impactOccurred];
}
#pragma mark - Lazy Init
- (UIButton *)button
{
if (!_button)
{
_button = [[UIButton alloc]init];
_button.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:_button];
[_button.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES;
[_button.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;
[_button setTitle:@"Impact" forState:UIControlStateNormal];
[_button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
}
return _button;
}
@end