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

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

所以我希望能够将一个字符串提供给键盘,为它提供预测的上下文.因此,如果用户被问及一个可以解释为极性的问题(是/否),那么预测键盘应该是“是”不|也许

这是开发人员可以使用的吗?

请注意,我不是在说自定义键盘,只是给标准键盘提供了一些上下文,因为它是预测的.我也不关心实际定制快速类型的回复as in this question.我只是希望键盘知道它是什么打字.

解决方法

严格地将建议输入到键盘是不可能的.但是,如果您想为用户提供相同的体验,我将使用myTextView.autocorrectionType = UITextAutocorrectionTypeNo隐藏iOS建议栏;然后用我自己的自定义视图替换该视图,模仿建议视图直到.一旦用户键入字符或选择了一个选项,然后隐藏自定义建议视图并重新启用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,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.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

要将其实现为您已经子类化的UITextField或UITextView,请导入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];
}

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...