自定义PopView

改代码是参考一个Demo直接改的,代码中有一些漏洞,如果发现其他的问题,可以下方直接留言

.h文件

#import <UIKit/UIKit.h>
typedef void(^PopoverBlock)(NSInteger index);
@interface CustomPopView : UIView
//@property(nonatomic,copy)void(^block)(int index);
//-(void)setDataArr:(NSArray *)titleArr withView:(id *)view withBlock:(void(^)(NSString *a))block;
@property (nonatomic, copy) NSArray *menuTitles;
@property(nonatomic,copy)void(^PopoverHiddenBlock)(BOOL isHidden );
- (void)showFromView:(id)aView selected:(PopoverBlock)selected;
@end@interface PopoverArrow : UIView@end

 .m文件

#import "CustomPopView.h"
// 字体大小
#define kPopoverFontSize 14.f// 十六进制颜色
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]#define SCREEN_W [UIScreen mainScreen].bounds.size.width
#define SCREEN_H [UIScreen mainScreen].bounds.size.height// 箭头高度
#define kArrowH 8
// 箭头宽度
#define kArrowW 15
//每行的高度
#define CELL_HEIGHT 38
//
#define Identifier @"cell"// 边框颜色
#define kBorderColor UIColorFromRGB(0xE1E2E3)
@interface CustomPopView () <UITableViewDelegate, UITableViewDataSource>
{PopoverBlock _selectedBlock;UIView *_backgroundView;PopoverArrow *_arrowView;
}@property (nonatomic, retain) UITableView *tableView;@end@implementation CustomPopView
- (instancetype)initWithFrame:(CGRect)frame
{if (!(self = [super initWithFrame:frame])) return nil;self.backgroundColor = [UIColor clearColor];// 箭头_arrowView = [PopoverArrow new];[self addSubview:_arrowView];// tableView放在箭头底下, 用于箭头挡住tableView边框[self insertSubview:self.tableView belowSubview:_arrowView];return self;
}- (void)layoutSubviews
{[super layoutSubviews];// 设置tableView默认的分割线起终点位置if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {[self.tableView setSeparatorInset:UIEdgeInsetsZero];}if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {[self.tableView setLayoutMargins:UIEdgeInsetsZero];}self.tableView.layer.cornerRadius  = 5.f;self.tableView.layer.borderColor   = kBorderColor.CGColor;self.tableView.layer.borderWidth   = 1.f;
}#pragma mark -- getter- (UITableView *)tableView
{if (_tableView) return _tableView;_tableView = [UITableView new];_tableView.delegate        = self;_tableView.dataSource      = self;_tableView.rowHeight       = CELL_HEIGHT;_tableView.backgroundColor = [UIColor whiteColor];_tableView.showsVerticalScrollIndicator = NO;[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:Identifier];_tableView.tableFooterView = UIView.new;return _tableView;
}#pragma mark -- delegate- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{return self.menuTitles.count;
}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];cell.textLabel.font   = [UIFont systemFontOfSize:kPopoverFontSize];cell.textLabel.text   = [self.menuTitles objectAtIndex:indexPath.row];return cell;
}- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {[cell setSeparatorInset:UIEdgeInsetsZero];}if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {[cell setLayoutMargins:UIEdgeInsetsZero];}
}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{[UIView animateWithDuration:0.25 animations:^{self.alpha = 0;} completion:^(BOOL finished) {[_backgroundView removeFromSuperview];_backgroundView = nil;if (_selectedBlock) {_selectedBlock(indexPath.row);}[self removeFromSuperview];}];
}#pragma mark -- private
// 点击透明层隐藏
- (void)hide
{[UIView animateWithDuration:0.25 animations:^{self.alpha = 0;} completion:^(BOOL finished) {[_backgroundView removeFromSuperview];_backgroundView = nil;if(self.PopoverHiddenBlock){self.PopoverHiddenBlock(YES);}[self removeFromSuperview];}];
}#pragma mark -- public/*!*  @author lifution**  @brief 显示弹窗**  @param aView    箭头指向的控件*  @param selected 选择完成回调*/
- (void)showFromView:(id)aView selected:(PopoverBlock)selected
{if (selected) _selectedBlock = selected;//aView只能传两种参数,一种是UIView 另一种UIBarButtonItemif(!([aView isKindOfClass:[UIView class]] || [aView isKindOfClass:[UIBarButtonItem class]])){return;}UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;// 背景遮挡_backgroundView = UIView.new;_backgroundView.frame = keyWindow.bounds;_backgroundView.backgroundColor = [UIColor blackColor];_backgroundView.alpha = 0.2;_backgroundView.userInteractionEnabled = YES;[_backgroundView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)]];[keyWindow addSubview:_backgroundView];// 刷新数据更新contentSize[self.tableView reloadData];// 获取触发弹窗的按钮在window中的坐标CGRect triggerRect ;if([aView isKindOfClass:[UIView class]]){UIView *view = (UIView *)aView;triggerRect = [view convertRect:view.bounds toView:keyWindow];}else{UIView *bgView = [aView valueForKey:@"_view"];triggerRect = [bgView convertRect:bgView.bounds toView: keyWindow];}// 箭头指向的中心点CGFloat arrowCenterX = CGRectGetMaxX(triggerRect)-CGRectGetWidth(triggerRect)/2;// 取得标题中的最大宽度CGFloat maxWidth = 0;for (id obj in self.menuTitles) {if ([obj isKindOfClass:[NSString class]]) {CGSize titleSize = [obj sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kPopoverFontSize]}];if (titleSize.width > maxWidth) {maxWidth = titleSize.width;}}}CGFloat curWidth  = ((maxWidth+80)>SCREEN_W-30)?SCREEN_W-30:(maxWidth+80);CGFloat curHeight = CELL_HEIGHT*self.menuTitles.count+kArrowH;CGFloat curX      = arrowCenterX-curWidth/2;CGFloat curY      = CGRectGetMaxY(triggerRect)+10;// 如果箭头指向点距离屏幕右边减去5px不足curWidth的一半的话就重新设置curXif ((SCREEN_W-arrowCenterX-5)<curWidth/2) {curX = curX-(curWidth/2-(SCREEN_W-arrowCenterX-5));}// 如果箭头指向点距离屏幕左边加上5px不足curWidth的一半的话就重新设置curXif (arrowCenterX+5<curWidth/2) {curX = curX+(curWidth/2-arrowCenterX)+5;}//如果高度大于10行,则最高按10计算if(curHeight>CELL_HEIGHT*10+kArrowH){curHeight = CELL_HEIGHT*10+kArrowH;}self.frame           = CGRectMake(curX, curY - 18, curWidth, curHeight);_arrowView.frame     = CGRectMake(arrowCenterX-curX-kArrowW/2, 0, kArrowW, kArrowH+1);// 箭头高度 +1 遮挡住tableView的边框self.tableView.frame = CGRectMake(0, kArrowH, curWidth,curHeight - kArrowH );[keyWindow addSubview:self];self.alpha = 0;[UIView animateWithDuration:0.3 animations:^{self.alpha = 1;}];
}@end// 箭头
@implementation PopoverArrow- (instancetype)initWithFrame:(CGRect)frame
{if (!(self = [super initWithFrame:frame])) return nil;self.backgroundColor = [UIColor clearColor];return self;
}// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {[super drawRect:rect];// Drawing codeCGSize curSize = rect.size;CGContextRef context = UIGraphicsGetCurrentContext();CGContextSetLineWidth(context, 1);CGContextSetStrokeColorWithColor(context, kBorderColor.CGColor);CGContextSetFillColorWithColor(context, UIColor.whiteColor.CGColor);CGContextBeginPath(context);CGContextMoveToPoint(context, 0, curSize.height);CGContextAddLineToPoint(context, curSize.width/2, 0);CGContextAddLineToPoint(context, curSize.width, curSize.height);CGContextDrawPath(context, kCGPathFillStroke);
}@end

 使用:

view = [CustomPopView new];
view.menuTitles = @[@"1",@"2",@"3"]; 
UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addBtnClick:)];
self.navigationItem.rightBarButtonItem = item;-(void)addBtnClick:(UIBarButtonItem *)item{[view showFromView:item selected:^(NSInteger index) {}];
}

 

 

转载于:https://www.cnblogs.com/hualuoshuijia/p/9983821.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/387956.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

线控耳机监听

当耳机的媒体按键被单击后&#xff0c;Android系统会发出一个广播&#xff0c;该广播的携带者一个Action名为MEDIA_BUTTON的Intent。监听该广播便可以获取手机的耳机媒体按键的单击事件。 在Android中有个AudioManager类&#xff0c;该类会维护MEDIA_BUTTON广播的分发&#xf…

当编程语言掌握在企业手中,是生机还是危机?

2019年4月&#xff0c;Java的收费时代来临了&#xff01; Java是由Sun微系统公司在1995年推出的编程语言&#xff0c;2010年Oracle收购了Sun之后&#xff0c;Java的所有者也就自然变成了Oracle。2019年&#xff0c;Oracle宣布将停止Java 8更新的免费支持&#xff0c;未来Java的…

sql如何处理null值_如何正确处理SQL中的NULL值

sql如何处理null值前言 (Preface) A friend who has recently started learning SQL asked me about NULL values and how to deal with them. If you are new to SQL, this guide should give you insights into a topic that can be confusing to beginners.最近开始学习SQL的…

名言警句分享

“当你想做一件事&#xff0c;却无能为力的时候&#xff0c;是最痛苦的。”基拉大和转载于:https://www.cnblogs.com/yuxijun/p/9986489.html

文字创作类App分享-简书

今天我用Mockplus做了一套简书App的原型&#xff0c;这是一款文字创作类的App&#xff0c;用户通过写文、点赞等互动行为&#xff0c;提高自己在社区的影响力&#xff0c;打造个人品牌。我运用了Mockplus基础组件、交互组件、移动组件等多个组件库&#xff0c;简单拖拽&#xf…

数据可视化 信息可视化_动机可视化

数据可视化 信息可视化John Snow’s map of Cholera cases near London’s Broad Street.约翰斯诺(John Snow)在伦敦宽街附近的霍乱病例地图。 John Snow, “the father of epidemiology,” is famous for his cholera maps. These maps represent so many of our aspirations …

android 接听和挂断实现方式

转载▼标签&#xff1a; android 接听 挂断 it 分类&#xff1a; android应用技巧 参考&#xff1a;android 来电接听和挂断 支持目前所有版本 注意&#xff1a;android2.3版本及以上不支持下面的自动接听方法。 &#xff08;会抛异常&#xff1a;java.lang.Securi…

Eclipse External Tool Configration Notepad++

Location&#xff1a; C:\Program Files\Notepad\notepad.exe Arguments&#xff1a;  ${resource_loc} 转载于:https://www.cnblogs.com/rgqancy/p/9987610.html

利用延迟关联或者子查询优化超多分页场景

2019独角兽企业重金招聘Python工程师标准>>> MySQL并不是跳过offset行&#xff0c;而是取offsetN行&#xff0c;然后返回放弃前offset行&#xff0c;返回N行&#xff0c;那当offset 特别大的时候&#xff0c;效率就非常的低下&#xff0c;要么控制返回的总页数&…

客户流失_了解客户流失

客户流失Big Data Analytics within a real-life example of digital music service数字音乐服务真实示例中的大数据分析 Customer churn is a key predictor of the long term success or failure of a business. It is the rate at which customers are leaving your busine…

Java 动态加载class 并反射调用方法

反射方法&#xff1a; public static void main(String[] args) throws Exception { File filenew File("D:/classtest");//类路径(包文件上一层) URL urlfile.toURI().toURL(); ClassLoader loadernew URLClassLoader(new URL[]{url});//创…

Nginx:Nginx limit_req limit_conn限速

简介 Nginx是一个异步框架的Web服务器&#xff0c;也可以用作反向代理&#xff0c;负载均衡器和HTTP缓存&#xff0c;最常用的便是Web服务器。nginx对于预防一些攻击也是很有效的&#xff0c;例如CC攻击&#xff0c;爬虫&#xff0c;本文将介绍限制这些攻击的方法&#xff0c;可…

快速数据库框架_快速学习新的数据科学概念的框架

快速数据库框架重点 (Top highlight)数据科学 (Data Science) Success in data science and software engineering depends on our ability to continuously learn new models and concepts.数据科学和软件工程的成功取决于我们不断学习新模型和概念的能力。 Both domains are…

Linux实战教学笔记12:linux三剑客之sed命令精讲

第十二节 linux三剑客之sed命令精讲 标签&#xff08;空格分隔&#xff09;&#xff1a; Linux实战教学笔记-陈思齐 ---更多资料点我查看 1&#xff0c;前言 我们都知道&#xff0c;在Linux中一切皆文件&#xff0c;比如配置文件&#xff0c;日志文件&#xff0c;启动文件等等。…

activiti 为什么需要采用乐观锁?

乐观锁 为什么需要采用乐观锁&#xff1f; 由于activiti一个周期的transaction时间可能比较长&#xff0c;且同一流程实例中存在任务并发执行等场景。设计者将update、insert、delete事务性的操作推迟至command结束时完成&#xff0c;这样尽量降低锁冲突的概率&#xff0c;由…

Python实现三级菜单(字典和列表的使用)

menu { 北京: { 海淀: { 五道口: { soho: {}, 网易: {}, google: {} }, 中关村: { 爱奇艺: {}, 汽车之家: {}, 优酷: {} …

停止使用p = 0.05

How many of you use p0.05 as an absolute cut off? p ≥ 0.05 means not significant. No evidence. Nada. And then p < 0.05 great it’s significant. This is a crude way of using p-values, and hopefully I will convince you of this.你们中有多少人使用p 0.05作…

centos7系统根目录扩容

比如 点击了后 点击创建虚拟磁盘 选择一个 20G 然后启动虚拟机使用fdisk查看所有的磁盘 看是否新增了一个20G的硬盘 [rootlocalhost ~]# fdisk -l磁盘 /dev/sda&#xff1a;8589 MB, 8589934592 字节&#xff0c;16777216 个扇区 Units 扇区 of 1 * 512 512 bytes 扇区大小(…

instrumentation模拟很多activity的操作

android.app.Instrumentation好像原来是用来做测试的, 可以用来模拟很多activity的操作 主要代码如下 如果在文本框中输入24,或者25 点击按钮就能模拟音量加减键 键值可以查看android.view.KeyEvent [java] view plaincopy package com.qefee.testinstrumentation; import…

成像数据更好的展示_为什么更多的数据并不总是更好

成像数据更好的展示Over the past few years, there has been a growing consensus that the more data one has, the better the eventual analysis will be.在过去的几年中&#xff0c;越来越多的共识是&#xff0c;数据越多&#xff0c;最终的分析就越好。 However, just a…