下载地址  https://github.com/MugunthKumar/MKHorizMenuDemo
直接 加入MKHorizMenu目录即可
下载包地址 http://pan.baidu.com/share/link?shareid=2872269045&uk=923776187
//
// MyViewController.m
// MyTest
//
// Created by zy on 13-8-1.
// Copyright (c) 2013年 zy. All rights reserved.
// #import "MyViewController.h"
#import "JSContentView.h" @interface MyViewController (){ JSContentView *newView;
UIView *contentview;
} @property(nonatomic,retain)NSArray *mydata;
//缓存view
@property(nonatomic,retain)NSMutableDictionary *cacheDic;
@end @implementation MyViewController - (void)viewDidLoad
{
[super viewDidLoad];
self.cacheDic=[NSMutableDictionary dictionary];
self.view.backgroundColor=[UIColor whiteColor];
self.mydata=@[@"语文",@"数学",@"英语"];
MKHorizMenu *Menu=[[MKHorizMenu alloc] initWithFrame:CGRectMake(, , self.view.bounds.size.width, )];
Menu.dataSource=self;
Menu.itemSelectedDelegate=self; contentview=[[UIView alloc] initWithFrame:CGRectMake(,, , )];//内容view, [self.view addSubview:contentview];
[contentview release]; [self.view addSubview:Menu];
[self horizMenu:Menu itemSelectedAtIndex:];//默认是第一个选中
[Menu reloadData]; [Menu release];
} #pragma mark -MKHorizMenu DataSource - (UIColor*) backgroundColorForMenu:(MKHorizMenu*) tabView{
return [UIColor purpleColor];
}
- (int) numberOfItemsForMenu:(MKHorizMenu*) tabView{ return ;
} - (NSString*) horizMenu:(MKHorizMenu*) horizMenu titleForItemAtIndex:(NSUInteger) index{ return self.mydata[index];
} #pragma mark -MK Delegate
- (void)horizMenu:(MKHorizMenu*) horizMenu itemSelectedAtIndex:(NSUInteger) index{ for (UIView *child in contentview.subviews) {//先移除所有的view.
[child removeFromSuperview];
} NSString *tempstr=self.mydata[index];
if(![self.cacheDic objectForKey:tempstr]){
switch (index) {
case :
{
newView=[[JSContentView alloc] initWithFrame:contentview.bounds requestSEL:@selector(Requestdeta) aDelegate:self];
[contentview addSubview:newView];
[self.cacheDic setObject:newView forKey:tempstr];//放入缓存中
[newView release];
}
break;
case :
{
UIView *view=[[UIView alloc] initWithFrame:contentview.bounds];
view.backgroundColor=[UIColor redColor];
[contentview addSubview:view];
[self.cacheDic setObject:view forKey:tempstr]; [view release];
}
break;
case :
{
UIView *view=[[UIView alloc] initWithFrame:contentview.bounds];
view.backgroundColor=[UIColor yellowColor];
[contentview addSubview:view];
[self.cacheDic setObject:view forKey:tempstr]; [view release];
}
break; default:
break;
} }
else{
UIView *view=[self.cacheDic objectForKey:tempstr];
[contentview addSubview:view];
} } -(void)Requestdeta{
NSString *url=[NSString stringWithFormat:@"http://61.177.61.252/szzssw/taxCommon.action?code=1001&pagecode=%zi&menucode=3300000000",newView.Pagecode==?:newView.Pagecode];
//请求数据,重新刷新数据
[[JSNetWord ShareNetwork] NetWorkWithConnctId: body:url PostBody:nil aDelegate:self];
//先从缓存中读取
NSString *cache=[self readApiCacheFileName:@"1.txt"]; if (cache.length> &&newView.Pagecode==) {
[self NetWorkWithConnectId: aBackString:cache withState:];
} } -(void)NetWorkWithConnectId:(int)connectid aBackString:(NSString *)backString withState:(int)state{
if(connectid==){ if (newView.Pagecode<= && state==) {//是下拉
newView.tableview.pullTableIsRefreshing=NO;
}
if (newView.Pagecode>) {//上拉
newView.tableview.pullTableIsLoadingMore=NO;
}
if (newView.Pagecode==) {//下拉 保存数据
[self saveApiCacheFileName:@"1.txt" textContent:backString Append:NO];
}
NSDictionary *arr= [backString JSONValue];
if (newView.Pagecode== &&newView.mydata.count>) {
[newView.mydata removeAllObjects];//下拉 只显示20 ,上拉 累加
}
[newView.mydata addObjectsFromArray:arr[@"content"]]; [newView.tableview reloadData]; }
} - (void)dealloc
{
[_mydata release];
[_cacheDic release];
[super dealloc];
} - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

第一种方式   修改 MKHorizMenu.m文件

-(void) reloadData
{
NSArray *viewsToRemove = [self subviews];
for (UIView *v in viewsToRemove) {
[v removeFromSuperview];
}
self.itemCount = [dataSource numberOfItemsForMenu:self];//调用代理的方法 float btnWidth = self.bounds.size.width / self.itemCount;//得到宽度 int tag = kButtonBaseTag; self.backgroundColor = [dataSource backgroundColorForMenu:self];
// self.selectedImage = [dataSource selectedItemImageForMenu:self]; 去掉代理这个方法 CGRect imgRec,btnRec,hRec;
CGRectDivide(self.bounds, &imgRec, &btnRec, , CGRectMaxYEdge); for(int i = ; i < self.itemCount; i ++)//进行遍历
{
CGRectDivide(btnRec, &hRec, &btnRec, btnWidth, CGRectMinXEdge);
NSString *title = [dataSource horizMenu:self titleForItemAtIndex:i];
UIButton *menuBtn = [UIButton ButtonWithImageName:nil hImageName:nil frame:CGRectZero title:title titleColor:[UIColor blackColor]
font:[UIFont boldSystemFontOfSize:] target:self action:@selector(buttonTapped:)];
// [menuBtn setBackgroundImage:self.selectedImage forState:UIControlStateSelected];
[menuBtn setTitleColor:rgb(, , ) forState:UIControlStateSelected]; menuBtn.tag = tag++;
[self addSubview:menuBtn]; if (i == ) {//按钮之间保持2个间距
hRec = UIEdgeInsetsInsetRect(hRec, UIEdgeInsetsMake(, , , ));
}else if (i == self.itemCount-){
hRec = UIEdgeInsetsInsetRect(hRec, UIEdgeInsetsMake(, , , ));
}else{
hRec = UIEdgeInsetsInsetRect(hRec, UIEdgeInsetsMake(, , , ));
}
menuBtn.frame = hRec; if (i != && i != self.itemCount) {//在每个按钮加 “|”
hRec = CGRectMake(hRec.origin.x, hRec.origin.y, , hRec.size.height);
hRec = UIEdgeInsetsInsetRect(hRec, UIEdgeInsetsMake(, , , ));
UIImageView *verImgView = [UIImageView ImageViewImageName:nil frame:hRec];
verImgView.image = [UIImage ImageWithColor:rgb(, , ) frame:verImgView.bounds];
[self addSubview:verImgView];
}
}
//这个在按钮中加背景
UIImageView *btnBottnImg = [UIImageView ImageViewImageName:nil frame:imgRec];
btnBottnImg.image = [UIImage ImageWithColor:rgb(, , ) frame:btnBottnImg.bounds];
[self addSubview:btnBottnImg]; //移动背景
moveImageView = [UIImageView ImageViewImageName:nil frame:UIEdgeInsetsInsetRect(imgRec, UIEdgeInsetsMake(, , , (self.itemCount - ) * btnWidth))];
moveImageView.image = [UIImage ImageWithColor:rgb(, , ) frame:moveImageView.bounds]; [self addSubview:moveImageView]; }
break;
} [self layoutSubviews]; } -(void) buttonTapped:(id) sender//按钮点击事件
{
UIButton *button = (UIButton*) sender; for(int i = ; i < self.itemCount; i++)
{
UIButton *thisButton = (UIButton*) [self viewWithTag:i + kButtonBaseTag];
if(i + kButtonBaseTag == button.tag)
thisButton.selected = YES;
else
thisButton.selected = NO;
}
CGRect mRec = moveImageView.frame;
moveImageView.frame = CGRectMake(button.frame.origin.x,mRec.origin.y, button.frame.size.width, mRec.size.height);//移动背景 [self.itemSelectedDelegate horizMenu:self itemSelectedAtIndex:button.tag - kButtonBaseTag];
}

第二种方式 修改 MKHorizMenu.m文件

//
// MKHorizMenu.m
// 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 "MKHorizMenu.h"
#define kButtonBaseTag 10000
#define kLeftOffset 10 @implementation MKHorizMenu @synthesize titles = _titles;
@synthesize selectedImage = _selectedImage; @synthesize itemSelectedDelegate;
@synthesize dataSource;
@synthesize itemCount = _itemCount; -(void) awakeFromNib
{
self.bounces = YES;
self.scrollEnabled = YES;
self.alwaysBounceHorizontal = YES;
self.alwaysBounceVertical = NO;
self.showsHorizontalScrollIndicator = NO;
self.showsVerticalScrollIndicator = NO;
[self reloadData];
} -(void) reloadData
{
NSArray *viewsToRemove = [self subviews];
for (UIView *v in viewsToRemove) {
[v removeFromSuperview];
} self.itemCount = [dataSource numberOfItemsForMenu:self];
self.backgroundColor = [dataSource backgroundColorForMenu:self];
//self.selectedImage = [dataSource selectedItemImageForMenu:self]; 去掉背景色 UIFont *buttonFont = [UIFont boldSystemFontOfSize:];
int buttonPadding = ; int tag = kButtonBaseTag;
// int xPos = kLeftOffset;
//fix 增加 自定义宽度和高度
int width=self.bounds.size.width/self.itemCount;
int height=self.bounds.size.height;
//
for(int i = ; i < self.itemCount; i ++)
{
NSString *title = [dataSource horizMenu:self titleForItemAtIndex:i];
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setTitle:title forState:UIControlStateNormal];
customButton.titleLabel.font = buttonFont; //[customButton setBackgroundImage:self.selectedImage forState:UIControlStateSelected];//去掉button的背景 customButton.tag = tag++;
[customButton addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; int buttonWidth = [title sizeWithFont:customButton.titleLabel.font
constrainedToSize:CGSizeMake(, )
lineBreakMode:UILineBreakModeClip].width;
customButton.frame=CGRectMake(i*width, , width, height);//设置uttton通的宽度和高度
// customButton.frame = CGRectMake(xPos, 7, buttonWidth + buttonPadding, 28);
// xPos += buttonWidth;
// xPos += buttonPadding;
[self addSubview:customButton];
} // bretdabaker: added right padding to contentSize
// xPos += kLeftOffset; // self.contentSize = CGSizeMake(xPos, 41);
[self layoutSubviews];
} -(void) setSelectedIndex:(int) index animated:(BOOL) animated
{
UIButton *thisButton = (UIButton*) [self viewWithTag:index + kButtonBaseTag];
thisButton.selected = YES;
[self setContentOffset:CGPointMake(thisButton.frame.origin.x - kLeftOffset, ) animated:animated];
[self.itemSelectedDelegate horizMenu:self itemSelectedAtIndex:index];
} -(void) buttonTapped:(id) sender
{
UIButton *button = (UIButton*) sender; for(int i = ; i < self.itemCount; i++)
{
UIButton *thisButton = (UIButton*) [self viewWithTag:i + kButtonBaseTag];
if(i + kButtonBaseTag == button.tag)
thisButton.selected = YES;
else
thisButton.selected = NO;
} [self.itemSelectedDelegate horizMenu:self itemSelectedAtIndex:button.tag - kButtonBaseTag];
} - (void)dealloc
{
[_selectedImage release];
_selectedImage = nil;
[_titles release];
_titles = nil; [super dealloc];
} @end

分析

MKHorizMenu.m文件
#import "MKHorizMenu.h"
#define kButtonBaseTag 10000
#define kLeftOffset 10 @implementation MKHorizMenu @synthesize titles = _titles;
@synthesize selectedImage = _selectedImage; @synthesize itemSelectedDelegate;
@synthesize dataSource;
@synthesize itemCount = _itemCount; -(void) awakeFromNib
{
self.bounces = YES;
self.scrollEnabled = YES;
self.alwaysBounceHorizontal = YES;
self.alwaysBounceVertical = NO;
self.showsHorizontalScrollIndicator = NO;
self.showsVerticalScrollIndicator = NO;
[self reloadData];
} -(void) reloadData
{
NSArray *viewsToRemove = [self subviews];
for (UIView *v in viewsToRemove) {
[v removeFromSuperview];
} self.itemCount = [dataSource numberOfItemsForMenu:self];//得到多少按钮
self.backgroundColor = [dataSource backgroundColorForMenu:self];//得到背景色
self.selectedImage = [dataSource selectedItemImageForMenu:self];//得到背景图片 UIFont *buttonFont = [UIFont boldSystemFontOfSize:];
int buttonPadding = ;//间距 int tag = kButtonBaseTag;
int xPos = kLeftOffset; for(int i = ; i < self.itemCount; i ++)
{
NSString *title = [dataSource horizMenu:self titleForItemAtIndex:i];//得到标题
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setTitle:title forState:UIControlStateNormal];
customButton.titleLabel.font = buttonFont;//设置字体 [customButton setBackgroundImage:self.selectedImage forState:UIControlStateSelected];//设置图片 customButton.tag = tag++;//设置tag
[customButton addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];//添加事件 int buttonWidth = [title sizeWithFont:customButton.titleLabel.font
constrainedToSize:CGSizeMake(, )
lineBreakMode:UILineBreakModeClip].width; customButton.frame = CGRectMake(xPos, , buttonWidth + buttonPadding, );//设置每个button的位置
xPos += buttonWidth;
xPos += buttonPadding;
[self addSubview:customButton];
} // bretdabaker: added right padding to contentSize
xPos += kLeftOffset; self.contentSize = CGSizeMake(xPos, );
[self layoutSubviews];
} -(void) setSelectedIndex:(int) index animated:(BOOL) animated//点击时触发事件。
{
UIButton *thisButton = (UIButton*) [self viewWithTag:index + kButtonBaseTag];
thisButton.selected = YES;
[self setContentOffset:CGPointMake(thisButton.frame.origin.x - kLeftOffset, ) animated:animated];
[self.itemSelectedDelegate horizMenu:self itemSelectedAtIndex:index];//事件
} -(void) buttonTapped:(id) sender
{
UIButton *button = (UIButton*) sender; for(int i = ; i < self.itemCount; i++)
{
UIButton *thisButton = (UIButton*) [self viewWithTag:i + kButtonBaseTag];
if(i + kButtonBaseTag == button.tag)
thisButton.selected = YES;
else
thisButton.selected = NO;
} [self.itemSelectedDelegate horizMenu:self itemSelectedAtIndex:button.tag - kButtonBaseTag];//点击事件
} - (void)dealloc
{
[_selectedImage release];
_selectedImage = nil;
[_titles release];
_titles = nil; [super dealloc];
} @end
 

ios中MKHorizMenu用法的更多相关文章

  1. ios 中pickerView用法之国旗选择

    QRViewController控制器 // // QRViewController.m // #import "QRViewController.h" #import " ...

  2. ios 中手势用法

    pan拖动手势 - (void)viewDidLoad { [super viewDidLoad]; [self Pan]; // Do any additional setup after load ...

  3. iOS中block的用法 以及和函数用法的区别

    ios中block的用法和函数的用法大致相同 但是block的用法的灵活性更高: 不带参数的block: void ^(MyBlock)() = ^{}; 调用的时候  MyBlock(); 带参数的 ...

  4. 【IOS】ios中NSUserDefault与android中的SharedPreference用法简单对比

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/3405308.html 有Android开发经验的朋友对Shar ...

  5. iOS中Block的用法,举例,解析与底层原理(这可能是最详细的Block解析)

    1. 前言 Block:带有自动变量(局部变量)的匿名函数.它是C语言的扩充功能.之所以是拓展,是因为C语言不允许存在这样匿名函数. 1.1 匿名函数 匿名函数是指不带函数名称函数.C语言中,函数是怎 ...

  6. IOS中的Block与C++11中的lambda

    ios中的block 可以说是一种函数指针,但更确切的讲,其实际上其应该算是object-c对C++11中lambda的支持或者说是一个语言上的变体,其实际内容是一样的,C++的lambda我已经有简 ...

  7. iOS中几种常用的数据存储方式

    自己稍微总结了一下下,方便大家查看 1.write直接写入文件的方法 永久保存在磁盘中,可以存储的对象有NSString.NSArray.NSDictionary.NSData.NSNumber,数据 ...

  8. iOS中使用 Reachability 检测网络

    iOS中使用 Reachability 检测网络 内容提示:下提供离线模式(Evernote).那么你会使用到Reachability来实现网络检测.   写本文的目的 了解Reachability都 ...

  9. Cordoval在iOS中的运用整理

    一:关于Cordoval理论知识 1:PhoneGap是手机平台上流行的一款中间件.它构建在各种手机平台所提供的WebView(浏览器内核)组件的基础之上,使用javascript语言对应用开发者提供 ...

随机推荐

  1. go语言之进阶篇字符串转换

    1.字符串转换 示例: package main import ( "fmt" "strconv" ) func main() { //转换为字符串后追加到字节 ...

  2. 遭遇sql server 2005 启动包未能正确加载需要重新安装错误,重装.NET FRAMEWORK经历分析

    开发的机器,系统情况如下: 1.server 2003 sp2 x86 2.补丁安装360 3.升级到IE8 因为担心server 2003 sp2 不能够自动update,最近都是用360打补丁,比 ...

  3. MFC中如何给静态文本框添加消息响应

    需要两个步骤: 第一个: 是改变它的ID(默认情况下所有的静态文本框的ID都为IDC_STATIC,你需要改变他的ID为其他的值). 第二个: 是在它的属性对话框中选中Notify选项,VS是将该属性 ...

  4. PHP文件操作[总结]

    1.前言 工作中涉及到数据处理,后台需要用到PHP处理数据,之前没有接触过PHP,借此机会了解了一下PHP,PHP很方便,很灵活,编码很舒服,很喜欢用PHP处理后台数据.今天总结一下php文件操作,主 ...

  5. centos6默认python2.6升级2.7 卸载python2.6升级2.7

    转自:http://blog.csdn.net/u010098331/article/details/52190354 本文介绍CentOS 6.3从自带的Pyhon版本是2.6升级到2.7.6的方法 ...

  6. Nginx 用log_format设置日志格式

    1.配置文件#vim /usr/local/nginx/conf/nginx.conflog_format access ‘$remote_addr – $remote_user [$time_loc ...

  7. JQuery 之 在数据加载完成后才自动执行函数

    数据加载完成执行: $(window).load(function(){ ... }); 进入页就执行,不论等数据是否加载完成: $(document).ready(function(){ ... } ...

  8. robot framework-databaselibaray库使用(python)

    公司做项目用到了databaselibaray,刚开始使用时碰到了很多问题,网上也查阅了很多资料终于是可以用了,现在整理记录下来,有需要的同学可随意使用: 另,本文主要是databaselibaray ...

  9. 带你走进EJB--将EJB发布为Webservice(1)

    Web service是一个平台独立,松耦合基于可编程的web的应用程序,可使用开放的XML标准来描述.发布.发现.协调和配置这些应用程序,用于开发分布式的互操作的应用程序. 简单说Web servi ...

  10. hibernate update 只更新部分字段的3种方法(其实我只想说第二种)

    hibernate 中如果直接使用Session.update(Object o);会把这个表中的所有字段更新一遍. 比如: public class Teacher Test { @Test pub ...