您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 自製下拉列表控件完整實作教學

編輯:iOS 開發綜合

在 iOS 的公開 API 中,並沒有直接提供「下拉列表」這樣的控件。若產品需要類似網頁 select 的互動效果,最直覺的做法是自行封裝一個複合控件:上方放一個 UITextField 作為觸發入口,下方掛一個隐藏的 UITableView 作為選項容器,再透過切換 frame 來模擬「展開/收合」的動感。

以下示範一個名為 DropDownList 的 UIView 子類,它同時扮演 UITableView 的 delegate 與 dataSource,並把「是否展開」的狀態交給 showList 屬性統一管理。

一、標頭檔:宣告屬性與公開方法

#import <UIKit/UIKit.h>

@interface DropDownList : UIView <UITableViewDelegate, UITableViewDataSource> {
    UITextField *textField;   // 文字輸入框
    NSArray *list;            // 下拉列表資料
    BOOL showList;            // 是否展開下拉列表
    UITableView *listView;    // 下拉列表本體
    CGRect oldFrame, newFrame; // 收合與展開時各自的矩形
    UIColor *lineColor, *listBgColor; // 邊框色與背景色
    CGFloat lineWidth;        // 邊框粗細
    UITextBorderStyle borderStyle; // 文字框邊框樣式
}

@property (nonatomic, retain) UITextField *textField;
@property (nonatomic, retain) NSArray *list;
@property (nonatomic, retain) UITableView *listView;
@property (nonatomic, retain) UIColor *lineColor, *listBgColor;
@property (nonatomic, assign) UITextBorderStyle borderStyle;

- (void)drawView;
- (void)setShowList:(BOOL)b;

@end

二、初始化:把「收合」與「展開」兩種尺寸先算好

建構子負責填入一組預設值:三個示範選項、圓角邊框、灰色分隔線、白色背景,以及一像素的線寬。同時把 self.backgroundColor 設為 clearColor,否則父視圖會露出一圈難看的黑邊。

#import "DropDownList.h"

@implementation DropDownList

@synthesize textField, list, listView, lineColor, listBgColor, borderStyle;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // 預設的下拉選項
        list = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4", nil];

        borderStyle = UITextBorderStyleRoundedRect;
        showList = NO;              // 預設不展開
        oldFrame = frame;           // 未展開時的尺寸

        // 展開後的高度為原本的 5 倍
        newFrame = CGRectMake(frame.origin.x,
                              frame.origin.y,
                              frame.size.width,
                              frame.size.height * 5);

        lineColor   = [UIColor lightGrayColor];
        listBgColor = [UIColor whiteColor];
        lineWidth   = 1;

        self.backgroundColor = [UIColor clearColor];
        [self drawView];
    }
    return self;
}

三、drawView:組裝文字框與列表

- (void)drawView {
    // 文字框
    textField = [[UITextField alloc]
                 initWithFrame:CGRectMake(0, 0,
                                          oldFrame.size.width,
                                          oldFrame.size.height)];
    textField.borderStyle = borderStyle;
    [self addSubview:textField];
    [textField addTarget:self
                  action:@selector(dropdown)
        forControlEvents:UIControlEventAllTouchEvents];

    // 下拉列表
    listView = [[UITableView alloc]
                initWithFrame:CGRectMake(lineWidth,
                                         oldFrame.size.height + lineWidth,
                                         oldFrame.size.width - lineWidth * 2,
                                         oldFrame.size.height * 4 - lineWidth * 2)];
    listView.dataSource = self;
    listView.delegate = self;
    listView.backgroundColor = listBgColor;
    listView.separatorColor = lineColor;
    listView.hidden = !showList;   // 依狀態顯示或隱藏

    [self addSubview:listView];
    [listView release];
}

四、dropdown:避免被其他控件遮住的關鍵

點擊文字框時先收起鍵盤,若列表已展開則直接返回;否則呼叫 bringSubviewToFront: 把自己提到最上層,再切換 showList。少了這一行,下拉出來的選項很可能被後加入的兄弟視圖蓋住。

- (void)dropdown {
    [textField resignFirstResponder];
    if (showList) {
        return;   // 已經展開,什麼都不做
    } else {
        // 提到最前,避免被其他控件遮住
        [self.superview bringSubviewToFront:self];
        [self setShowList:YES];
    }
}

五、列表的資料源與委派

#pragma mark - listView dataSource & delegate

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellid = @"listviewid";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:cellid] autorelease];
    }
    cell.textLabel.text = (NSString *)[list objectAtIndex:indexPath.row];
    cell.textLabel.font = textField.font;
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return oldFrame.size.height;
}

// 選取某列:把文字寫回文字框並收合
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    textField.text = (NSString *)[list objectAtIndex:indexPath.row];
    [self setShowList:NO];
}

六、以 frame 切換完成展開動畫

- (BOOL)showList {
    return showList;
}

- (void)setShowList:(BOOL)b {
    showList = b;
    if (showList) {
        self.frame = newFrame;
    } else {
        self.frame = oldFrame;
    }
    listView.hidden = !b;
}

- (void)dealloc {
    [super dealloc];
}

@end

整份實作的核心觀念其實只有一個:把「展開」視為一次尺寸變化,而不是新增一個彈出視圖。好處是控件自帶 layout 邏輯,放到任何父視圖裡都能沿用原本的座標體系;缺點則是展開時會佔用版面空間,若父視圖採用固定配置,記得預留高度或改用 overlay 呈現。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved