ios - 可以以编程方式提供 iOS 预测键盘上下文/源文本吗?

标签 ios ios8 quicktype

我正在开发一个消息传递应用程序,希望 iOS 8 中的预测键盘能够识别正在撰写消息的用户正在回复上一条消息。

所以我希望能够向键盘输入一个字符串,为它提供预测上下文。因此,如果用户被问到一个可以解释为极性(是/否)的问题,那么预测键盘应该有 Yes |否 |也许

这对开发者可用吗?

请注意,我不是在谈论自定义键盘,只是为标准键盘提供一些预测上下文。我也不关心实际自定义快速类型回复 as in this question .我只想让键盘知道它在输入什么。

最佳答案

严格按照默认键盘输入建议是不可能的。但是,如果您想为用户提供相同的体验,我会使用 myTextView.autocorrectionType = UITextAutocorrectionTypeNo; 隐藏 iOS 建议栏,然后用我自己的模仿建议 View 的自定义 View 替换该 View 直到。一旦用户键入一个字符或选择一个选项,然后隐藏自定义建议 View 并重新启用 iOS 建议栏。

我为此对 UIInputView 进行了子类化(透明度和过渡有点偏差,但其他一切都很好相当)。

#import <UIKit/UIKit.h>

@protocol SuggestionViewDelegate <NSObject>

@required
- (void)suggestionSelected:(NSString *)suggestion;

@end

@interface SuggestionView : UIInputView

- (instancetype)init;
- (instancetype)initWithFrame:(CGRect)frame;

/**
 *  The list of suggestions being displayed.
 *  The array contains 0-3 strings.
 *
 *  @return Array of NSString's representing the current suggested strings
 */
- (NSArray *)suggestions;

/**
 *  Add a suggestion to display in the view.
 *  If there are already maxSuggestionCount suggestions, the added suggestion will push one of them out.
 *  If there are already maxSuggestionCount suggestions and the input is 'nil' then the last suggestion will be removed.
 *
 *  @param suggestion String to suggest to the user
 */
- (void)addSuggestion:(NSString *)suggestion;

/**
 *  Removes the suggestion from the list of displayed suggestions.
 *  If the string is not in the set then there is no change made.
 *
 *  @param suggestion NSString to remove from the suggested strings
 */
- (void)removeSuggestion:(NSString *)suggestion;

/**
 *  Takes in either NSArray or NSSet and replaces 'suggestions' with the input. 
 *  Only the first three arguments are recognized.
 *  Objects should be strings. Undefined behavior otherwise.
 *
 *  @param suggestions NSArray or NSSet with 0-3 NSStrings
 */
- (void)setSuggestions:(NSObject *)suggestions;

@property (weak) id <SuggestionViewDelegate> delegate;

/**
 *  The maximum number of suggestions allowed. Default is 3.
 */
@property (nonatomic) NSInteger maxSuggestionCount;

@end
#import "SuggestionView.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width

@implementation SuggestionView {
    NSMutableOrderedSet *_suggestions;
    NSMutableArray *_suggestionButtons;
}

- (instancetype)init {
    self = [self initWithFrame:CGRectMake(0.0f, 0.0f, kScreenWidth, 36.0f)];

    if (self) {

    }

    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame inputViewStyle:UIInputViewStyleKeyboard];

    if (self) {
        _suggestions = [[NSMutableOrderedSet alloc] initWithCapacity:3];
        self.maxSuggestionCount = 3;
        _suggestionButtons = [[NSMutableArray alloc] init];
        self.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.04f];
    }

    return self;
}

#pragma mark - Modifying Suggestions

- (void)addSuggestion:(NSString *)suggestion {
    if (suggestion) {
        [_suggestions addObject:suggestion];
    }

    while (_suggestions.count > self.maxSuggestionCount) {
        [_suggestions removeObjectAtIndex:self.maxSuggestionCount];
    }
}

- (void)removeSuggestion:(NSString *)suggestion {
    [_suggestions removeObject:suggestion];
}

- (void)setSuggestions:(NSObject *)suggestions {
    if ([suggestions respondsToSelector:@selector(countByEnumeratingWithState:objects:count:)]) {
        [_suggestions removeAllObjects];

        for (NSString *suggestion in (NSArray *)suggestions) {
            if (_suggestions.count < self.maxSuggestionCount) {
                [_suggestions addObject:suggestion];
            } else {
                break;
            }
        }
    }
}

- (NSArray *)suggestions {
    NSMutableArray *suggestionsArray = [[NSMutableArray alloc] initWithCapacity:_suggestions.count];
    for (NSString *suggestion in _suggestions) {
        [suggestionsArray addObject:suggestion];
    }

    return suggestionsArray;
}

#pragma mark - Visual Layout of Suggestions

- (void)layoutSubviews {
    [self layoutSuggestions];
}

- (void)layoutSuggestions {
    for (UIView *subview in _suggestionButtons) {
        [subview removeFromSuperview];
    }

    [_suggestionButtons removeAllObjects];

    for (int i = 0; i < _suggestions.count; i++) {
        NSString *suggestion = _suggestions[i];
        UIButton *suggestionButton = [[UIButton alloc] initWithFrame:CGRectMake(i * self.bounds.size.width/_suggestions.count, 0.0f, self.bounds.size.width/_suggestions.count, self.bounds.size.height)];
        [suggestionButton setTitle:suggestion forState:UIControlStateNormal];
        suggestionButton.titleLabel.adjustsFontSizeToFitWidth = YES;
        suggestionButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        [suggestionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [suggestionButton addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:suggestionButton];

        if (i > 0) {
            UIView *whiteLine = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.5f, self.bounds.size.height)];
            whiteLine.backgroundColor = [UIColor whiteColor];
            [suggestionButton addSubview:whiteLine];
        }

        [_suggestionButtons addObject:suggestionButton];
    }
}

#pragma mark - Selecting a Suggestion

- (void)buttonTouched:(UIButton *)button {
    NSTimeInterval animationDuration = 0.09f;
    [UIView animateWithDuration:animationDuration animations:^{
        [button setBackgroundColor:[UIColor whiteColor]];

        if ([self.delegate respondsToSelector:@selector(suggestionSelected:)]) {
            [self performSelector:@selector(suggestionSelected:) withObject:button.currentTitle afterDelay:animationDuration * 0.9f];
        }

        [button performSelector:@selector(setBackgroundColor:) withObject:[UIColor clearColor] afterDelay:animationDuration];
    }];
}

- (void)suggestionSelected:(NSString *)suggestion {
    if ([self.delegate respondsToSelector:@selector(suggestionSelected:)]) {
        [self.delegate suggestionSelected:suggestion];
    }
}

@end

要将此实现到您已经子类化的 UITextFieldUITextView 中,请导入 SuggestionView 并实现 SuggestionViewDelegate。然后,在 UITextFieldDelegate(或 UITextViewDelegate)方法中,添加:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([textField isEqual:self.messageTextField]) {
        if (self.suggestionView.suggestions.count > 0 && textField.text.length == 0) {
            textField.inputAccessoryView = self.suggestionView;
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            [textField reloadInputViews];
        }
    }

    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField isEqual:self.messageTextField]) {
        if (string.length > 0) {
            [self removeSuggestionView];
        }
    }

    return YES;
}


- (void)removeSuggestionView {
    self.messageTextField.inputAccessoryView = nil;
    [self.messageTextField setInputAccessoryView:nil];
    self.messageTextField.autocorrectionType = UITextAutocorrectionTypeYes;
    [self.messageTextField reloadInputViews];

    [self.messageTextField performSelector:@selector(resignFirstResponder) withObject:self afterDelay:0.0f];
    [self.messageTextField performSelector:@selector(becomeFirstResponder) withObject:self afterDelay:0.0f];
}

然后,实现SuggestionViewDelegate:

- (void)suggestionSelected:(NSString *)suggestion {
    [self.messageTextField setText:[NSString stringWithFormat:@"%@%@ ", self.messageTextField.text, suggestion]];
    [self removeSuggestionView];
}

虽然这不是一个完美的解决方案,但它确实产生了预期的效果。

关于ios - 可以以编程方式提供 iOS 预测键盘上下文/源文本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28889368/

相关文章:

ios - Scenekit 中自定义几何体的纹理坐标

ios - Quicktype 选项参数处理

iphone - 在 iOS 5 中检测用户对 MKMapView 的触摸

iOS - 如何将文件从一个应用程序发送到其他特定应用程序

ios - 为什么升级到 ios-sdk8 后我的 UIImageView 不会拉伸(stretch)?

objective-c - iOS8 中的相机旋转和 OverlayView

cocoa-touch - QuickType 预测会考虑应该被我的 UITextFieldDelegate 阻止的击键

ios - 现在不可能从 didFinishPickingMediaWithInfo 方法中关闭图像选择器吗?

swift - 1 个 View Controller 中数据的不同表示