MKHorizMenu 源码地址 

现在想要实现以下效果,其中“选时间”这部分是一个NavigationBar,“日期”是横向的菜单,“电影时段”是TableView。

iOS 横向菜单

比较难实现的是横向菜单,因为没有直接的控件可以用。开始我想用之前的方法,将TableView和TableViewCell倒置,实现横向TableView;但是会出现一个问题,每个Cell中的文本,都被省略显示,类似显示“2月...”。

原因是,在倒置TableView之前,TableView的宽很小(相当于图中横向菜单的高),那么文本写在上面就会被省略显示,虽然TableView倒置过来了,但是文本还是原来的文本,并没有因为倒置后宽变长了而全部显示。

只能试试别的方法,发现MKHorizMenu这个开源库。

 

MKHorizMenu的实现原理是将UISrollView封装,声明DataSource协议和Delegate协议。详见。由于自带Demo是使用nib,所以我在MKHorizMenu.m中将初始化方法awakeFromNib改为initWithFrame。

//
//  MKHorizMenu.h
//  MKHorizMenuDemo
//
//  Created by Mugunth on 09/05/11.
//  Copyright 2011 Steinlogic. All rights reserved.

//  Permission granted to do anything, commercial/non-commercial with this file apart from removing the line/URL above
//  Read my blog post at http://mk.sg/8h on how to use this code

//  As a side note on using this code, you might consider giving some credit to me by
//    1) linking my website from your app's website
//    2) or crediting me inside the app's credits page
//    3) or a tweet mentioning @mugunthkumar
//    4) A paypal donation to mugunth.kumar@gmail.com
//
//  A note on redistribution
//    While I'm ok with modifications to this source code,
//    if you are re-publishing after editing, please retain the above copyright notices

#import <UIKit/UIKit.h>

@class MKHorizMenu;

@protocol MKHorizMenuDataSource <NSObject>
@required
- (UIImage*)selectedItemImageForMenu:(MKHorizMenu*)tabView;
- (UIColor*)backgroundColorForMenu:(MKHorizMenu*)tabView;
- (NSUInteger)numberOfItemsForMenu:(MKHorizMenu*)tabView;

- (NSString*)horizMenu:(MKHorizMenu*)horizMenu titleForItemAtIndex:(NSUInteger)index;
@end

@protocol MKHorizMenuDelegate <NSObject>
@required
- (void)horizMenu:(MKHorizMenu*)horizMenu itemSelectedAtIndex:(NSUInteger)index;
@end

@interface MKHorizMenu : UIScrollView
{

    int _itemCount;
    UIImage* _selectedImage;
    NSMutableArray* _titles;
    id<MKHorizMenuDataSource> dataSource;
    id<MKHorizMenuDelegate> itemSelectedDelegate;
}

@property (nonatomic, retain) NSMutableArray* titles;
@property (nonatomic, retain) id<MKHorizMenuDelegate> itemSelectedDelegate;
@property (nonatomic, retain) id<MKHorizMenuDataSource> dataSource;
@property (nonatomic, retain) UIImage* selectedImage;
@property (nonatomic, assign) int itemCount;

- (void)reloadData;
- (void)setSelectedIndex:(int)index animated:(BOOL)animated;
@end
MKHorizMenu.h

相关文章: