下载地址  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(0, 0, self.view.bounds.size.width, 80)];Menu.dataSource=self;Menu.itemSelectedDelegate=self;contentview=[[UIView alloc] initWithFrame:CGRectMake(0,90, 320, 300)];//内容view,
    [self.view addSubview:contentview];[contentview release];[self.view addSubview:Menu];[self  horizMenu:Menu itemSelectedAtIndex:0];//默认是第一个选中
    [Menu reloadData];[Menu release];
}#pragma mark -MKHorizMenu DataSource- (UIColor*) backgroundColorForMenu:(MKHorizMenu*) tabView{return [UIColor purpleColor];
}
- (int) numberOfItemsForMenu:(MKHorizMenu*) tabView{return 3;
}- (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 0:{newView=[[JSContentView alloc] initWithFrame:contentview.bounds requestSEL:@selector(Requestdeta) aDelegate:self];[contentview addSubview:newView];[self.cacheDic setObject:newView forKey:tempstr];//放入缓存中
                [newView release];}break;case 1:{UIView *view=[[UIView alloc] initWithFrame:contentview.bounds];view.backgroundColor=[UIColor redColor];[contentview addSubview:view];[self.cacheDic setObject:view forKey:tempstr];[view release];}break;case 2:{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==0?1:newView.Pagecode];//请求数据,重新刷新数据[[JSNetWord ShareNetwork] NetWorkWithConnctId:100 body:url PostBody:nil aDelegate:self];//先从缓存中读取NSString *cache=[self readApiCacheFileName:@"1.txt"];if (cache.length>0 &&newView.Pagecode==1) {[self NetWorkWithConnectId:100 aBackString:cache withState:0];}}-(void)NetWorkWithConnectId:(int)connectid aBackString:(NSString *)backString withState:(int)state{if(connectid==100){if (newView.Pagecode<=1 && state==1) {//是下拉newView.tableview.pullTableIsRefreshing=NO;}if (newView.Pagecode>1) {//上拉newView.tableview.pullTableIsLoadingMore=NO;}if (newView.Pagecode==1) {//下拉 保存数据[self saveApiCacheFileName:@"1.txt" textContent:backString Append:NO];}NSDictionary *arr= [backString JSONValue];if (newView.Pagecode==1 &&newView.mydata.count>0) {[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, 2, CGRectMaxYEdge);for(int i = 0 ; 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:15] target:self action:@selector(buttonTapped:)];//        [menuBtn setBackgroundImage:self.selectedImage forState:UIControlStateSelected];[menuBtn setTitleColor:rgb(109, 209, 62) forState:UIControlStateSelected];menuBtn.tag = tag++;[self addSubview:menuBtn];if (i == 0) {//按钮之间保持2个间距hRec = UIEdgeInsetsInsetRect(hRec, UIEdgeInsetsMake(0, 0, 0, 1));}else if (i == self.itemCount-1){hRec = UIEdgeInsetsInsetRect(hRec, UIEdgeInsetsMake(0, 1, 0, 0));}else{hRec = UIEdgeInsetsInsetRect(hRec, UIEdgeInsetsMake(0, 1, 0, 1));}menuBtn.frame = hRec;if (i != 0 && i != self.itemCount) {//在每个按钮加 “|”hRec = CGRectMake(hRec.origin.x, hRec.origin.y,2 , hRec.size.height);hRec = UIEdgeInsetsInsetRect(hRec, UIEdgeInsetsMake(10, 0, 10, 0));UIImageView *verImgView = [UIImageView ImageViewImageName:nil frame:hRec];verImgView.image = [UIImage ImageWithColor:rgb(213, 214, 218) frame:verImgView.bounds];[self addSubview:verImgView];}}//这个在按钮中加背景UIImageView *btnBottnImg = [UIImageView ImageViewImageName:nil frame:imgRec];btnBottnImg.image = [UIImage ImageWithColor:rgb(213, 214, 218) frame:btnBottnImg.bounds];[self addSubview:btnBottnImg];//移动背景moveImageView = [UIImageView ImageViewImageName:nil frame:UIEdgeInsetsInsetRect(imgRec, UIEdgeInsetsMake(0, 0, 0, (self.itemCount - 1) * btnWidth))];moveImageView.image = [UIImage ImageWithColor:rgb(109, 209, 62) frame:moveImageView.bounds];[self addSubview:moveImageView];}break;}[self layoutSubviews];}-(void) buttonTapped:(id) sender//按钮点击事件
{UIButton *button = (UIButton*) sender;for(int i = 0; i < self.itemCount; i++){UIButton *thisButton = (UIButton*) [self viewWithTag:i + kButtonBaseTag];if(i + kButtonBaseTag == button.tag)thisButton.selected = YES;elsethisButton.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:15];int buttonPadding = 25;int tag = kButtonBaseTag;
//    int xPos = kLeftOffset;//fix 增加 自定义宽度和高度int width=self.bounds.size.width/self.itemCount;int height=self.bounds.size.height;//
    for(int i = 0 ; 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.fontconstrainedToSize:CGSizeMake(150, 28) lineBreakMode:UILineBreakModeClip].width;customButton.frame=CGRectMake(i*width, 0, 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, 0) animated:animated];[self.itemSelectedDelegate horizMenu:self itemSelectedAtIndex:index];
}-(void) buttonTapped:(id) sender
{UIButton *button = (UIButton*) sender;for(int i = 0; i < self.itemCount; i++){UIButton *thisButton = (UIButton*) [self viewWithTag:i + kButtonBaseTag];if(i + kButtonBaseTag == button.tag)thisButton.selected = YES;elsethisButton.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:15];int buttonPadding = 25;//间距int tag = kButtonBaseTag;    int xPos = kLeftOffset;for(int i = 0 ; 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.fontconstrainedToSize:CGSizeMake(150, 28) lineBreakMode:UILineBreakModeClip].width;customButton.frame = CGRectMake(xPos, 7, buttonWidth + buttonPadding, 28);//设置每个button的位置xPos += buttonWidth;xPos += buttonPadding;[self addSubview:customButton];        }// bretdabaker: added right padding to contentSizexPos += 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, 0) animated:animated];[self.itemSelectedDelegate horizMenu:self itemSelectedAtIndex:index];//事件
}-(void) buttonTapped:(id) sender
{UIButton *button = (UIButton*) sender;for(int i = 0; i < self.itemCount; i++){UIButton *thisButton = (UIButton*) [self viewWithTag:i + kButtonBaseTag];if(i + kButtonBaseTag == button.tag)thisButton.selected = YES;elsethisButton.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. SQLite3在IOS中的用法

    {http://blog.csdn.net/mamong/article/details/8365466} 使用的过程根据使用的函数大致分为如下几个过程: sqlite3_open() sqlite3 ...

  2. iOS中CAShapeLayer用法

    (1)画虚线 CAShapeLayer *shapeLayer = [CAShapeLayer layer]; [shapeLayer setBounds:self.bounds]; [shapeLa ...

  3. iOS 中DLog 用法

    Objective C中NSLog虽然使用方便,但是有时候NSLog并不能满足程序员调试程序的全部需求.比如打印的结果位于哪个类中?是在哪个类中打印的?或者具体是在哪行打印的等等.所以对于程序员来说急 ...

  4. 关于iOS 中DLog 用法

    DLog的使用 Objective C中NSLog虽然使用方便,但是有时候NSLog并不能满足程序员调试程序的全部需求.比如打印的结果位于哪个类中?是在哪个类中打印的?或者具体是在哪行打印的等等.所以 ...

  5. IOS中NSUserDefaults的用法

    2019独角兽企业重金招聘Python工程师标准>>> IOS中NSUserDefaults的用法(轻量级本地数据存储) 分类: IOS开发 Object-C编程语言2012-09- ...

  6. ios开发 ajax hook,IOS中的网络拦截总结

    因为业务场景需要,要求对App中网络请求进行拦截.这里包括原生网络请求和WebView里的网络请求.之前我们了解过原生网络请求的拦截是可以实现的,但是WebView中网络请求似乎还不太可能,所以抱着尝 ...

  7. [转] iOS中@class #import #include 简介

    [转载自:http://blog.csdn.net/chengwuli125/article/details/9705315] 一.解析        很多刚开始学习iOS开发的同学可能在看别人的代码 ...

  8. ios中关于delegate(委托)的使用心得

    ios中关于delegate(委托)的使用心得 分类: iOS开发2012-05-15 10:54 34793人阅读 评论(9) 收藏 举报 iosuiviewtimerinterfaceprinti ...

  9. IOS中扩展机制Category和associative

    在ios开发中,有时候会遇到以下的问题,需要在一个类中添加自己的一些属性和方法.一般的做法是重写一个类来继承它,但是有时候就只是需要添加一些简单的属性和方法,那么这样做就显得过于麻烦,其实在IOS中还 ...

最新文章

  1. openface 和openpose(pytorch)剪枝之路
  2. 下列哪个不是目前python里的内置模块-不吹不擂,你想要的Python面试都在这里了【315+道题】...
  3. boost::geometry::model::d3::point_xyz用法的测试程序
  4. [Kafka与Spark集成系列四] Spark运行结构
  5. 如何理解和分析linux系统的CPU平均负载情况(load average)
  6. react实战课程_在使用React一年后,我学到的最重要的课程
  7. python入坑指南_Rust入坑指南:万物初始
  8. sd卡和sdio sdhc_想买TF卡,那些标注卡上的参数看懂了么?
  9. 清华计算机系教学计划,清华大学电子信息科学与技术教学计划
  10. 目标检测(十一)--ConvNets目标检测概述
  11. JDK打印的疑问:CUPSPrinter有何用处?
  12. python xlwt写excel_Python使用xlwt写excel并设置写入格式
  13. 领导周末喊程序员修错误,程序员霸气回应:在下卖艺不是卖身!
  14. java-家庭作业1
  15. python文件seek函数,Python 文件操作seek()函数
  16. Java基础篇--概念理解(泛型、注解)
  17. 老程序员到40、50岁该怎么办?是继续留在软件行业还是转行?是默默死去还是向中层管理者蜕变?美国在老程序员的职业发展上的经验?...
  18. 广西清华计算机专业兄弟,2017年清华大学清华在广西录取圆满结束
  19. 路径MTU(PMTU)发现控制与DF位
  20. 网页中HTML代码如何实现字体删除线效果

热门文章

  1. matlab安装_走进数模(三)MATLAB安装
  2. python爬虫模块_python实现爬虫的模块总结
  3. r语言多重共线性_R语言与计量经济学(二)多重共线性
  4. vue 怎么样不重复往数组里插入数据_Vue.js在数组中插入重复数据的实现代码分享...
  5. win2003服务器通过ipsec做防火墙的配置方法
  6. IIS6下配置fastcgi的php的教程
  7. 使用SSH+SFTP操作终端全解析,告别XShell
  8. Java中console类的简单用法
  9. iOS之一个iOS开发人员完整的学习路线
  10. jquery对select的操作详解