自定義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.pswp.cn/news/387956.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387956.shtml
英文地址,請注明出處:http://en.pswp.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…