在集合视图控制器中播放键盘单击声音

Ber*_*lue 6 objective-c ios uicollectionview

我创建了一个用作自定义一个UICollectionViewController的子类inputAccessoryViewControllerUITextView. https://developer.apple.com/reference/uikit/uiresponder/1621124-inputaccessoryviewcontroller

当您使用playInputClick点击集合视图中的单元格时,我想播放键盘单击声音. https://developer.apple.com/reference/uikit/uidevice/1620050-playinputclick

我无法弄清楚如何在集合视图中使用它.它适用于这样的简单视图使用a的inputAccessoryView属性,UITextView但我不确定在集合视图控制器层次结构中的子类视图,以获得键盘单击声音.

@interface KeyboardClickView : UIView <UIInputViewAudioFeedback>
@end

@implementation KeyboardClickView
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [self addGestureRecognizer:tap];
    }
    return self;
}

- (void)tap:(id)sender
{
    [[UIDevice currentDevice] playInputClick];
}

- (BOOL)enableInputClicksWhenVisible
{
    return YES;
}
@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{   
    _inputAccessoryView = [[KeyboardClickView alloc] initWithFrame:CGRectMake(0, 0, 0, 50)];
    _inputAccessoryView.backgroundColor = [UIColor redColor];
    [[UITextView appearance] setInputAccessoryView:_inputAccessoryView];

    // ...
}
@end
Run Code Online (Sandbox Code Playgroud)

我也知道您可以使用键盘单击声音,AudioServicesPlaySystemSound(1104)但如果他们禁用了键盘单击声音,则这不符合用户的设置.

Cas*_*sey 1

不要使用 a UICollectionViewController,而是定义KeyboardClickView为 a 的子类UICollectionView并将其放置在 a 上UIViewController

@interface KeyboardClickView : UICollectionView <UIInputViewAudioFeedback>

- (id)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
    self = [super initWithFrame:frame collectionViewLayout:layout];

    // existing implementation
Run Code Online (Sandbox Code Playgroud)

新的视图控制器可能看起来像这样:

@interface KeyboardClickViewController: UIViewController <UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) KeyboardClickView *clickView;
@end

@implementation KeyboardClickViewController

-(void)viewDidLoad {
    [super viewDidLoad];

    self.clickView = [[KeyboardClickView alloc] initWithFrame:self.view.bounds collectionViewLayout:[UICollectionViewFlowLayout new]];
    self.clickView.delegate = self;
    self.clickView.dataSource = self;
    [self.view addSubview:self.clickView];
}

// existing UICollectionViewController logic

@end
Run Code Online (Sandbox Code Playgroud)

playInputClick这允许您从 aUIView而不是 a进行调用UIViewController