UITextField 实现下拉显示自动补全列表

在别人的代码基础上自己又修改了1部分,增加了删除功能.自动调整高度功能.还有部分没完善的地方,使用时候自己可以适当调整.


先看实现效果.


类代码:

//
//  AutocompletionTableView.h
//
//  Created by Gushin Arseniy on 11.03.12.
//  Copyright (c) 2012 Arseniy Gushin. All rights reserved.
//

#import <UIKit/UIKit.h>

// Consts for AutoCompleteOptions:
//
// if YES - suggestions will be picked for display case-sensitive
// if NO - case will be ignored
#define ACOCaseSensitive @"ACOCaseSensitive"

// if "nil" each cell will copy the font of the source UITextField
// if not "nil" given UIFont will be used
#define ACOUseSourceFont @"ACOUseSourceFont"

// if YES substrings in cells will be highlighted with bold as user types in
// *** FOR FUTURE USE ***
#define ACOHighlightSubstrWithBold @"ACOHighlightSubstrWithBold"

// if YES - suggestions view will be on top of the source UITextField
// if NO - it will be on the bottom
// *** FOR FUTURE USE ***
#define ACOShowSuggestionsOnTop @"ACOShowSuggestionsOnTop"

@protocol AutocompletionTableViewDelegate;

@interface AutocompletionTableView : UITableView <UITableViewDataSource, UITableViewDelegate>
// Dictionary of NSStrings of your auto-completion terms
@property (nonatomic, strong) NSArray *suggestionsDictionary; 

// Dictionary of auto-completion options (check constants above)
@property (nonatomic, strong) NSDictionary *options;

//delegate
@property (nonatomic, assign) id<AutocompletionTableViewDelegate>  tabDelegate;
// Call it for proper initialization
- (UITableView *)initWithTextField:(UITextField *)textField inViewController:(UIViewController *) parentViewController withOptions:(NSDictionary *)options;

@end

@protocol AutocompletionTableViewDelegate <NSObject>

- (void) autoCompletionTableView:(AutocompletionTableView *) completionView
                    deleteString:(NSString *) sString;
//点击序号
- (void) autoCompletionTableView:(AutocompletionTableView *) completionView
                 didSelectString:(NSString *) sString;

@end

//
//  AutocompletionTableView.m
//
//  Created by Gushin Arseniy on 11.03.12.
//  Copyright (c) 2012 Arseniy Gushin. All rights reserved.
//

#import "AutocompletionTableView.h"

#define TABLEVIEW_MAX_HEIGHT    120

@interface AutocompletionTableView () 
@property (nonatomic, strong) NSArray *suggestionOptions; // of selected NSStrings 
@property (nonatomic, strong) UITextField *textField; // will set automatically as user enters text
@property (nonatomic, strong) UIFont *cellLabelFont; // will copy style from assigned textfield

- (void) resizingTableHeight;

@end

@implementation AutocompletionTableView

@synthesize suggestionsDictionary = _suggestionsDictionary;
@synthesize suggestionOptions = _suggestionOptions;
@synthesize textField = _textField;
@synthesize cellLabelFont = _cellLabelFont;
@synthesize options = _options;
@synthesize tabDelegate = _tabDelegate;

#pragma mark - Initialization
- (UITableView *)initWithTextField:(UITextField *)textField inViewController:(UIViewController *) parentViewController withOptions:(NSDictionary *)options
{
    //set the options first
    self.options = options;
    CGRect frame;
    // frame must align to the textfield 
    frame = CGRectMake(textField.frame.origin.x, 
                                  textField.frame.origin.y + textField.frame.size.height, 
                                  textField.frame.size.width, 
                                  TABLEVIEW_MAX_HEIGHT);

    
    
    // save the font info to reuse in cells
    self.cellLabelFont = textField.font;
    
    self = [super initWithFrame:frame
             style:UITableViewStylePlain];
    
    self.delegate = self;
    self.dataSource = self;
    self.scrollEnabled = YES;
    
    // turn off standard correction
    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    
    // to get rid of "extra empty cell" on the bottom
    // when there's only one cell in the table
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, textField.frame.size.width, 1)]; 
    v.backgroundColor = [UIColor clearColor];
    [self setTableFooterView:v];
    self.hidden = YES;  
    
    //在uiview 下面
    if (textField.superview.superview == nil) {
        [parentViewController.view addSubview:self];
    } else {
        [textField.superview addSubview:self];
    }

    self.alpha = 0.85;
    
    
    [textField addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [textField addTarget:self action:@selector(textFieldBeginEdit:) forControlEvents:UIControlEventEditingDidBegin];
    [textField addTarget:self action:@selector(textFieldEndEdit:) forControlEvents:UIControlEventEditingDidEnd];
    [textField addTarget:self action:@selector(textFieldDidEndOnExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    return self;
}

- (void) resizingTableHeight {
    NSInteger nCount = self.suggestionOptions.count;
    
    CGRect frame = self.frame;
    
    if (nCount * 44.0 < TABLEVIEW_MAX_HEIGHT) {
        frame.size.height = nCount * 44.0;
    } else {
        frame.size.height = TABLEVIEW_MAX_HEIGHT;
    }
    self.frame = frame;
}

#pragma mark - Logic staff
- (BOOL) substringIsInDictionary:(NSString *)subString
{
    NSMutableArray *tmpArray = [NSMutableArray array];
    NSRange range;
    
    for (NSString *tmpString in self.suggestionsDictionary)
    {
        range = ([[self.options valueForKey:ACOCaseSensitive] isEqualToNumber:[NSNumber numberWithInt:1]]) ? [tmpString rangeOfString:subString] : [tmpString rangeOfString:subString options:NSCaseInsensitiveSearch];
        if (range.location != NSNotFound) [tmpArray addObject:tmpString];
    }
    if ([tmpArray count]>0)
    {
        self.suggestionOptions = tmpArray;
        return YES;
    }
    return NO;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.suggestionOptions.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
    if (cell == nil) 
    {
        cell = [[UITableViewCell alloc] 
                 initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier];
        UIView *selectBackView = [[UIView alloc] initWithFrame:cell.frame];
        selectBackView.backgroundColor = [UIColor colorWithRed:201.0 / 255.0 
                                                         green:201.0 / 255.0 
                                                          blue:201.0 / 255.0 
                                                         alpha:1];
        cell.selectedBackgroundView = selectBackView;
        [selectBackView release];
        
//        UIView *accView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//        button.frame = CGRectMake(0, 0, 30, 30);
//        [accView addSubview:button];
//        cell.accessoryView = accView;
//        [accView release];
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    }
    
    if ([self.options valueForKey:ACOUseSourceFont]) 
    {
        cell.textLabel.font = [self.options valueForKey:ACOUseSourceFont];
    } else {
        cell.textLabel.font = self.cellLabelFont;
    }
    cell.textLabel.adjustsFontSizeToFitWidth = NO;
    cell.textLabel.text = [self.suggestionOptions objectAtIndex:indexPath.row];

    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tabDelegate &&
        [_tabDelegate respondsToSelector:@selector(autoCompletionTableView:didSelectString:)]) {
        [_tabDelegate autoCompletionTableView:self 
                              didSelectString:[self.suggestionOptions objectAtIndex:indexPath.row]];
    }
    [self.textField setText:[self.suggestionOptions objectAtIndex:indexPath.row]];
    [self hideOptionsView];
}

- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (_tabDelegate &&
            [_tabDelegate respondsToSelector:@selector(autoCompletionTableView:deleteString:)]) {
            [_tabDelegate autoCompletionTableView:self deleteString:[self.suggestionOptions objectAtIndex:indexPath.row]];
        }
        
        [self showOptionsView];
        self.suggestionOptions = [NSMutableArray arrayWithArray:_suggestionsDictionary];
        [self reloadData];
    }
}

- (void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    
    [self tableView:tableView commitEditingStyle:UITableViewCellEditingStyleDelete forRowAtIndexPath:indexPath];
}

#pragma mark - UITextField delegate
- (void)textFieldValueChanged:(UITextField *)textField
{
    self.textField = textField;
    NSString *curString = textField.text;
    
    if (![curString length])
    {
        [self textFieldBeginEdit:textField];
        return;
    } else if ([self substringIsInDictionary:curString]) {
            [self reloadData];
            [self showOptionsView];
    } else {
            [self hideOptionsView];
    }
}

- (void) textFieldBeginEdit:(UITextField *) textField {
    if ([textField.text length] == 0) {
        self.suggestionOptions = [NSMutableArray arrayWithArray:_suggestionsDictionary];
        [self reloadData];
        [self showOptionsView];
       
    }
}

- (void) textFieldEndEdit:(UITextView *) textField {
    [self hideOptionsView];
}

- (void) textFieldDidEndOnExit:(UITextField *) textField {
    [self hideOptionsView];
}

#pragma mark - Options view control
- (void)showOptionsView
{
    [self resizingTableHeight];
    self.hidden = NO;
}

- (void) hideOptionsView
{
    self.hidden = YES;
}

@end


使用代码:


- (AutocompletionTableView *)autoCompleter
{
    if (!_autoCompleter)
    {
        NSMutableDictionary *options = [NSMutableDictionary dictionaryWithCapacity:2];
        [options setValue:[NSNumber numberWithBool:YES] forKey:ACOCaseSensitive];
        [options setValue:nil forKey:ACOUseSourceFont];
        
        _autoCompleter = [[AutocompletionTableView alloc] initWithTextField:self.fieldUserName inViewController:self withOptions:options];
        _autoCompleter.tabDelegate = self;
        _autoCompleter.suggestionsDictionary = [CWDataBaseModel loginUserNames];
    }
    return _autoCompleter;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值