text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```objective-c // // WMTimeLineHeaderView.h // WeChat // // Created by zhengwenming on 2017/9/18. // #import <UIKit/UIKit.h> #import "JGGView.h" #import "MessageInfoModel.h" @interface WMTimeLineHeaderView : UITableViewHeaderFooterView @property(nonatomic,retain)MessageInfoModel *model; ///** // * block // */ @property (nonatomic, copy)TapBlcok tapImageBlock; @end ```
/content/code_sandbox/WeChat/ViewController/Discover发现-朋友圈/朋友圈-单个tableView/WMTimeLineHeaderView.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
100
```objective-c // // CommentInfoModel.m // WeChat // // Created by zhengwenming on 2017/9/21. // #import "CommentInfoModel.h" @implementation CommentInfoModel -(instancetype)initWithDic:(NSDictionary *)dic{ self = [super init]; if (self) { self.commentId = dic[@"commentId"]; self.commentUserId = dic[@"commentUserId"]; self.commentUserName = dic[@"commentUserName"]; self.commentPhoto = dic[@"commentPhoto"]; self.commentText = dic[@"commentText"]; self.commentByUserId = dic[@"commentByUserId"]; self.commentByUserName = dic[@"commentByUserName"]; self.commentByPhoto = dic[@"commentByPhoto"]; self.createDateStr = dic[@"createDateStr"]; self.checkStatus = dic[@"checkStatus"]; //rowHeightattributedText NSString *str = nil; if (![self.commentByUserName isEqualToString:@""]) { str= [NSString stringWithFormat:@"%@%@%@", self.commentUserName, self.commentByUserName, self.commentText]; }else{ str= [NSString stringWithFormat:@"%@%@", self.commentUserName, self.commentText]; } NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:str]; [text addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, self.commentUserName.length)]; [text addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(self.commentUserName.length + 2, self.commentByUserName.length)]; UIFont *font = [UIFont systemFontOfSize:13.0]; [text addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, str.length)]; NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init]; if ([text.string isMoreThanOneLineWithSize:CGSizeMake(kScreenWidth - 2*kGAP-kAvatar_Size-10, CGFLOAT_MAX) font:font lineSpaceing:3.0]) {//margin style.lineSpacing = 3; }else{ style.lineSpacing = CGFLOAT_MIN; } [text addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, text.string.length)]; self.rowHeight = [text.string boundingRectWithSize:CGSizeMake(kScreenWidth - 2*kGAP-kAvatar_Size-10, CGFLOAT_MAX) font:font lineSpacing:3.0].height+0.5+3.0;//5.0 self.attributedText = text; } return self; } - (NSMutableArray *)commentModelArray { if (_commentModelArray == nil) { _commentModelArray = [[NSMutableArray alloc] init]; } return _commentModelArray; } -(NSMutableArray *)messageBigPics{ if (_messageBigPicArray==nil) { _messageBigPicArray = [NSMutableArray array]; } return _messageBigPicArray; } @end ```
/content/code_sandbox/WeChat/ViewController/Discover发现-朋友圈/朋友圈-单个tableView/CommentInfoModel.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
629
```objective-c // // WMTimeLineViewController.m // WeChat // // Created by zhengwenming on 2017/9/21. // #import "WMTimeLineViewController.h" #import "WMTimeLineHeaderView.h" #import "CommentCell.h" #import "LikeUsersCell.h" @interface WMTimeLineViewController ()<UITableViewDelegate,UITableViewDataSource> @property(nonatomic,strong)UITableView *tableView; @end @implementation WMTimeLineViewController -(UITableView *)tableView{ if (_tableView==nil) { _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavbarHeight, self.view.frame.size.width, kScreenHeight-kNavbarHeight) style:UITableViewStyleGrouped]; _tableView.dataSource = self; _tableView.delegate = self; _tableView.backgroundColor = [UIColor whiteColor]; _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag; _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; [_tableView registerClass:NSClassFromString(@"WMTimeLineHeaderView") forHeaderFooterViewReuseIdentifier:@"WMTimeLineHeaderView"]; [_tableView registerNib:[UINib nibWithNibName:@"LikeUsersCell" bundle:nil] forCellReuseIdentifier:@"LikeUsersCell"]; [_tableView registerClass:NSClassFromString(@"CommentCell") forCellReuseIdentifier:@"CommentCell"]; UIImageView * backgroundImageView= [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 260)]; backgroundImageView.image = [UIImage imageNamed:@"background.jpeg"]; _tableView.tableHeaderView = backgroundImageView; _tableView.contentInset = UIEdgeInsetsMake(-kNavbarHeight, 0, kBottomSafeHeight, 0); } return _tableView; } -(void)textViewDidSendText:(NSString *)text{ NSLog(@"%@",text); } /** frame */ - (void)keyboardChangeFrameMinY:(CGFloat)minY{ } #pragma mark - (void)viewDidLoad { [super viewDidLoad]; [self getTestData]; [self.view addSubview:self.tableView]; [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.mas_equalTo(0); }]; } -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return self.dataSource.count; } // -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ MessageInfoModel *eachModel = self.dataSource[section]; return eachModel.commentModelArray.count; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ MessageInfoModel *eachModel = self.dataSource[indexPath.section]; CommentInfoModel *commentModel = eachModel.commentModelArray[indexPath.row]; return commentModel.rowHeight; } -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ MessageInfoModel *eachModel = self.dataSource[section]; return eachModel.headerHeight; } -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ __weak __typeof(self) weakSelf= self; WMTimeLineHeaderView *headerView = (WMTimeLineHeaderView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"WMTimeLineHeaderView"]; headerView.tapImageBlock = ^(NSInteger index, NSArray *dataSource) { WMPhotoBrowser *browser = [WMPhotoBrowser new]; browser.dataSource = dataSource.mutableCopy; browser.currentPhotoIndex = index; [weakSelf.navigationController pushViewController:browser animated:YES]; // [weakSelf presentViewController:browser animated:YES completion:^{ // }]; }; MessageInfoModel *eachModel = self.dataSource[section]; headerView.model = eachModel; return headerView; } ///footer -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{ MessageInfoModel *messageModel = self.dataSource[section]; if (messageModel.commentModelArray.count) { return 10.f; } return CGFLOAT_MIN; } ///footerView - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section { UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 10.f)]; return footerView; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ MessageInfoModel *eachModel = self.dataSource[indexPath.section]; CommentInfoModel *commentModel = eachModel.commentModelArray[indexPath.row]; if (commentModel.likeUsersArray.count) { LikeUsersCell *likeUsersCell = (LikeUsersCell *)[tableView dequeueReusableCellWithIdentifier:@"LikeUsersCell"]; likeUsersCell.model = commentModel; return likeUsersCell; }else{ __weak __typeof(self) weakSelf= self; CommentCell *commentCell = (CommentCell *)[tableView dequeueReusableCellWithIdentifier:@"CommentCell"]; commentCell.model = commentModel; commentCell.tapCommentBlock = ^(CommentCell *cell, CommentInfoModel *model) { [weakSelf dealComment]; }; return commentCell; } } -(void)dealComment{ } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; NSLog(@"%s",__FUNCTION__); } -(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; NSLog(@"%s",__FUNCTION__); } @end ```
/content/code_sandbox/WeChat/ViewController/Discover发现-朋友圈/朋友圈-单个tableView/WMTimeLineViewController.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,058
```objective-c // // TimeLineBaseViewController.m // WeChat // // Created by zhengwenming on 2017/9/18. // #import "TimeLineBaseViewController.h" @implementation TimeLineBaseViewController -(NSMutableArray *)dataSource{ if (_dataSource==nil) { _dataSource = [NSMutableArray array]; } return _dataSource; } -(void)getTestData{ NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"]]]; NSDictionary * jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; for (NSDictionary *eachDic in jsonDic[@"data"][@"rows"]) { MessageInfoModel *messageModel = [[MessageInfoModel alloc] initWithDic:eachDic]; [self.dataSource addObject:messageModel]; } } - (void)viewDidLoad { [super viewDidLoad]; self.title = @""; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:[[YYFPSLabel alloc]initWithFrame:CGRectMake(0, 5, 60, 30)]]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end ```
/content/code_sandbox/WeChat/ViewController/Discover发现-朋友圈/朋友圈基类/TimeLineBaseViewController.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
244
```objective-c // // FriendInfoModel.h // WeChat // // Created by zhengwenming on 2017/9/21. // #import <Foundation/Foundation.h> @interface FriendInfoModel : NSObject @property(nonatomic,copy)NSString *imgName; @property(nonatomic,copy)NSString *photo; @property(nonatomic,copy)NSString *userName; @property(nonatomic,copy)NSString *userId; @property(nonatomic,copy)NSString *phoneNO; @property(nonatomic,assign)NSRange range; -(instancetype)initWithDic:(NSDictionary *)dic; @end ```
/content/code_sandbox/WeChat/ViewController/Discover发现-朋友圈/朋友圈基类/FriendInfoModel.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
102
```objective-c // // Layout.h // WeChat // // Created by zhengwenming on 2017/9/22. // #import <Foundation/Foundation.h> @interface Layout : NSObject @property (nonatomic, assign) CGRect frameLayout; @end ```
/content/code_sandbox/WeChat/ViewController/Discover发现-朋友圈/朋友圈基类/Layout.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
54
```objective-c // // TimeLineBaseViewController.h // WeChat // // Created by zhengwenming on 2017/9/18. // #import "BaseViewController.h" #import "MessageInfoModel.h" #import "WMPhotoBrowser.h" @interface TimeLineBaseViewController : BaseViewController @property(nonatomic,strong)NSMutableArray *dataSource; #pragma mark #pragma mark -(void)getTestData; @end ```
/content/code_sandbox/WeChat/ViewController/Discover发现-朋友圈/朋友圈基类/TimeLineBaseViewController.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
84
```objective-c // // FriendInfoModel.m // WeChat // // Created by zhengwenming on 2017/9/21. // #import "FriendInfoModel.h" @implementation FriendInfoModel -(instancetype)initWithDic:(NSDictionary *)dic{ self = [super init]; if (self) { self.userId = dic[@"userId"]; self.userName = dic[@"userName"]; self.photo = dic[@"photo"]; self.phoneNO = dic[@"phoneNO"]; } return self; } @end ```
/content/code_sandbox/WeChat/ViewController/Discover发现-朋友圈/朋友圈基类/FriendInfoModel.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
114
```objective-c // // Layout.m // WeChat // // Created by zhengwenming on 2017/9/22. // #import "Layout.h" @implementation Layout @end ```
/content/code_sandbox/WeChat/ViewController/Discover发现-朋友圈/朋友圈基类/Layout.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
41
```objective-c // // JGGView.h // AIHealth // // Created by on 2017/7/17. // #import <UIKit/UIKit.h> #define kGAP 10 /** * * @param index index * @param dataSource */ typedef void (^TapBlcok)(NSInteger index,NSArray *dataSource); @interface JGGView : UIView /** * dataSourceUIImageNSString(path_to_urlNSURL */ @property (nonatomic, retain)NSArray * dataSource; /** * TapBlcok */ @property (nonatomic, copy)TapBlcok tapBlock; @end ```
/content/code_sandbox/WeChat/View/JGGView.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
129
```objective-c // // JGGView.m // AIHealth // // Created by on 2017/7/17. // #import "JGGView.h" #import "YYAnimatedImageView.h" #import "UIImageView+WebCache.h" @implementation JGGView -(void)tapImageAction:(UITapGestureRecognizer *)tap{ UIImageView *tapView = (UIImageView *)tap.view; if (self.tapBlock) { self.tapBlock(tapView.tag,self.dataSource); } } -(void)setDataSource:(NSArray *)dataSource{ _dataSource = dataSource; // CGFloat jgg_width = kScreenWidth-2*kGAP-kAvatar_Size-50; CGFloat imageWidth = (jgg_width-2*kGAP)/3; CGFloat imageHeight = imageWidth; for (NSUInteger i=0; i<dataSource.count; i++) { YYAnimatedImageView *iv = [[YYAnimatedImageView alloc]initWithFrame:CGRectMake(0+(imageWidth+kGAP)*(i%3),floorf(i/3.0)*(imageHeight+kGAP),imageWidth, imageHeight)]; if ([dataSource[i] isKindOfClass:[UIImage class]]) { iv.image = dataSource[i]; }else if ([dataSource[i] isKindOfClass:[NSString class]]){ [iv sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",dataSource[i]]] placeholderImage:[UIImage imageNamed:@"placeholder"]]; // [iv setImageWithURL:[NSURL URLWithString:str] // placeholder:nil // options:YYWebImageOptionProgressiveBlur | YYWebImageOptionShowNetworkActivity | YYWebImageOptionSetImageWithFadeAnimation // progress:^(NSInteger receivedSize, NSInteger expectedSize) { // if (expectedSize > 0 && receivedSize > 0) { // CGFloat progress = (CGFloat)receivedSize / expectedSize; // progress = progress < 0 ? 0 : progress > 1 ? 1 : progress; // // } // } transform:nil // completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { // if (stage == YYWebImageStageFinished) { // // } // }]; }else if ([dataSource[i] isKindOfClass:[NSURL class]]){ [iv sd_setImageWithURL:dataSource[i] placeholderImage:[UIImage imageNamed:@"placeholder"]]; } iv.userInteractionEnabled = YES;//NO iv.tag = i; iv.autoPlayAnimatedImage = YES; [self addSubview:iv]; UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageAction:)]; [iv addGestureRecognizer:singleTap]; } } @end ```
/content/code_sandbox/WeChat/View/JGGView.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
563
```objective-c // // CopyAbleLabel.m // WeChat // // Created by zhengwenming on 2017/9/21. // #import "CopyAbleLabel.h" @interface CopyAbleLabel () @property(nonatomic,strong)UIColor *originalColor; @end @implementation CopyAbleLabel - (void)awakeFromNib { [super awakeFromNib]; [self setUp]; } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self setUp]; } return self; } -(void)setUp{ self.userInteractionEnabled = YES; UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressToCopy:)]; [self addGestureRecognizer:longPress]; } -(void)setBackgroundColor:(UIColor *)backgroundColor{ [super setBackgroundColor:backgroundColor]; if (self.originalColor==nil) { self.originalColor = backgroundColor; } } -(void)longPressToCopy:(UILongPressGestureRecognizer *)sender{ if (sender.state==UIGestureRecognizerStateBegan) { [sender.view becomeFirstResponder]; self.backgroundColor = [UIColor lightGrayColor]; UIMenuController *menuController = [UIMenuController sharedMenuController]; [menuController setTargetRect:sender.view.frame inView:self.superview]; [menuController setMenuVisible:YES animated:YES]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pasteboardHideNotice:) name:UIMenuControllerWillHideMenuNotification object:nil]; }else if (sender.state==UIGestureRecognizerStateCancelled){ }else if (sender.state==UIGestureRecognizerStateChanged){ }else if (sender.state==UIGestureRecognizerStateEnded){ } } -(void)pasteboardHideNotice:(NSNotification *)obj{ self.backgroundColor = self.originalColor; if (self) { [[NSNotificationCenter defaultCenter]removeObserver:self name:UIMenuControllerWillHideMenuNotification object:nil]; } } -(BOOL)canBecomeFirstResponder{ return YES; } -(BOOL)canPerformAction:(SEL)action withSender:(id)sender{ NSArray* methodNameArr = @[@"copy:"]; if ([methodNameArr containsObject:NSStringFromSelector(action)]) { return YES; } return [super canPerformAction:action withSender:sender]; } -(void)copy:(id)sender{ UIPasteboard* pasteboard = [UIPasteboard generalPasteboard]; if (self.tag==1000) { if ([self.text containsString:@":"]) { NSRange mhRange = [self.text rangeOfString:@":"]; pasteboard.string = [self.text substringFromIndex:mhRange.location+1]; pasteboard.string = self.text; }else{ pasteboard.string = self.text; } }else{ pasteboard.string = self.text; } } @end ```
/content/code_sandbox/WeChat/View/CopyAbleLabel.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
607
```objective-c // // CopyAbleLabel.h // WeChat // // Created by zhengwenming on 2017/9/21. // #import <UIKit/UIKit.h> @interface CopyAbleLabel : UILabel @end ```
/content/code_sandbox/WeChat/View/CopyAbleLabel.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
50
```objective-c // // UIBarButtonItem+addition.m // TongXueBao // // Created by on 16/10/19. // @implementation BackView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor clearColor]; } return self; } -(void)layoutSubviews{ [super layoutSubviews]; UINavigationBar *navBar = nil; UIView *aView = self.superview; while (aView) { if ([aView isKindOfClass:[UINavigationBar class]]) { navBar = (UINavigationBar *)aView; break; } aView = aView.superview; } UINavigationItem * navItem = (UINavigationItem *)navBar.items.lastObject; UIBarButtonItem *leftItem = navItem.leftBarButtonItem; UIBarButtonItem *rightItem = navItem.rightBarButtonItem; if (rightItem) {// BackView *backView = rightItem.customView; // backView.backgroundColor = [UIColor magentaColor]; // backView.btn.backgroundColor = [UIColor yellowColor]; if ([backView isKindOfClass:self.class]) { if ([[[UIDevice currentDevice] systemVersion]intValue]>=11) { // backView.btn.x = backView.width -backView.btn.width-20; backView.btn.x = backView.width -backView.btn.width; }else{ backView.btn.x = backView.width -backView.btn.width; } for (UIView *aView in backView.subviews) { if ([aView isKindOfClass:[UILabel class]]) { UILabel *textLabel = (UILabel *)aView; [backView bringSubviewToFront:textLabel]; } } } } if (leftItem) {// BackView *backView = leftItem.customView; // backView.backgroundColor = [UIColor magentaColor]; // backView.btn.backgroundColor = [UIColor yellowColor]; if ([[[UIDevice currentDevice] systemVersion]intValue]>=11) { }else{ // backView.btn.x = 20; } } } @end #import "UIBarButtonItem+addition.h" @implementation UIBarButtonItem (addition) + (UIBarButtonItem *)itemWithIcon:(NSString *)icon highIcon:(NSString *)highIcon target:(id)target action:(SEL)action { return [self.class itemWithIcon:icon highIcon:highIcon title:nil target:target action:action]; } + (UIBarButtonItem *)itemWithIcon:(NSString *)icon highIcon:(NSString *)highIcon title:(NSString *)title target:(id)target action:(SEL)action { BackView *customView = [[BackView alloc] initWithFrame:CGRectMake(0, 0, 80, 44)]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action]; [customView addGestureRecognizer:tap]; customView.btn = [UIButton buttonWithType:UIButtonTypeCustom]; customView.btn.titleLabel.font = [UIFont systemFontOfSize:16.0]; if (icon) { [customView.btn setBackgroundImage:[UIImage imageNamed:icon] forState:UIControlStateNormal]; } if (highIcon) { [customView.btn setBackgroundImage:[UIImage imageNamed:highIcon] forState:UIControlStateHighlighted]; } customView.btn.frame = CGRectMake(0, 0, customView.btn.currentBackgroundImage.size.width, customView.btn.currentBackgroundImage.size.height); customView.btn.centerY = customView.centerY; [customView.btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside]; [customView addSubview:customView.btn]; if (title.length) { customView.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(customView.btn.frame) + 5, CGRectGetMinY(customView.btn.frame), 80, 44)]; customView.titleLabel.centerY = customView.btn.centerY; customView.titleLabel.text = title; customView.titleLabel.textColor = [UIColor whiteColor]; customView.titleLabel.userInteractionEnabled = YES; [customView.titleLabel addGestureRecognizer:tap]; [customView addSubview:customView.titleLabel]; } return [[UIBarButtonItem alloc] initWithCustomView:customView]; } + (UIBarButtonItem *)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action { UIButton *btn = [[UIButton alloc] init]; [btn setTitle:title forState:UIControlStateNormal]; btn.titleLabel.font = [UIFont systemFontOfSize:15.0]; [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled]; [btn setTitleColor:kThemeColor forState:UIControlStateNormal]; [btn setTitleColor:kThemeColor forState:UIControlStateHighlighted]; [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside]; btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -15); btn.frame = CGRectMake(0, 0, title.length * 22, 30); // btn.backgroundColor = [UIColor redColor]; return [[UIBarButtonItem alloc] initWithCustomView:btn]; } @end ```
/content/code_sandbox/WeChat/Category/UIBarButtonItem+addition.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,059
```objective-c // // UILabel+TapAction.h // WeChat // // Created by zhengwenming on 2017/9/10. // #import <UIKit/UIKit.h> @protocol TapActionDelegate <NSObject> @optional /** * TapActionDelegate * * @param string * @param range range * @param index index */ - (void)tapReturnString:(NSString *)string range:(NSRange)range index:(NSInteger)index; @end @interface AttributeModel : NSObject @property (nonatomic, copy) NSString *str; @property (nonatomic, assign) NSRange range; @end @interface UILabel (TapAction) /** * */ @property (nonatomic, assign) BOOL enabledTapEffect; /** * Block * * @param strings * @param tapClick */ - (void)tapActionWithStrings:(NSArray <NSString *> *)strings tapClicked:(void (^) (NSString *string , NSRange range , NSInteger index))tapClick; /** * delegate * * @param strings * @param delegate delegate */ - (void)tapActionWithStrings:(NSArray <NSString *> *)strings delegate:(id <TapActionDelegate> )delegate; @end ```
/content/code_sandbox/WeChat/Category/UILabel+TapAction.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
263
```objective-c // // NSString+Extension.m // WeChat // // Created by zhengwenming on 2017/9/21. // #import "NSString+Extension.h" @implementation NSString (Extension) /** * */ - (CGSize)boundingRectWithSize:(CGSize)size paragraphStyle:(NSMutableParagraphStyle *)paragraphStyle font:(UIFont*)font { NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:self]; [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)]; [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.length)]; NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin; CGRect rect = [attributeString boundingRectWithSize:size options:options context:nil]; // NSLog(@"size:%@", NSStringFromCGSize(rect.size)); //1 if ((rect.size.height - font.lineHeight) <= paragraphStyle.lineSpacing) { if ([self containChinese:self]) { // rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing); } } return rect.size; } /** * */ - (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont*)font lineSpacing:(CGFloat)lineSpacing { NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:self]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = lineSpacing; [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)]; [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.length)]; NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin; CGRect rect = [attributeString boundingRectWithSize:size options:options context:nil]; // NSLog(@"size:%@", NSStringFromCGSize(rect.size)); //1 if ((rect.size.height - font.lineHeight) <= paragraphStyle.lineSpacing) { if ([self containChinese:self]) { // rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing); } } return rect.size; } /** * , */ - (CGFloat)boundingRectWithSize:(CGSize)size font:(UIFont*)font lineSpacing:(CGFloat)lineSpacing maxLines:(NSInteger)maxLines{ if (maxLines <= 0) { return 0; } CGFloat maxHeight = font.lineHeight * maxLines + lineSpacing * (maxLines - 1); CGSize orginalSize = [self boundingRectWithSize:size font:font lineSpacing:lineSpacing]; if ( orginalSize.height >= maxHeight ) { return maxHeight; }else{ return orginalSize.height; } } /** * */ - (BOOL)isMoreThanOneLineWithSize:(CGSize)size font:(UIFont *)font lineSpaceing:(CGFloat)lineSpacing{ if ( [self boundingRectWithSize:size font:font lineSpacing:lineSpacing].height > font.lineHeight ) { return YES; }else{ return NO; } } // - (BOOL)containChinese:(NSString *)str { for(int i=0; i< [str length];i++){ int a = [str characterAtIndex:i]; if( a > 0x4e00 && a < 0x9fff){ return YES; } } return NO; } @end ```
/content/code_sandbox/WeChat/Category/NSString+Extension.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
756
```objective-c // // NSString+Extension.h // WeChat // // Created by zhengwenming on 2017/9/21. // #import <Foundation/Foundation.h> @interface NSString (Extension) /** * */ - (CGSize)boundingRectWithSize:(CGSize)size paragraphStyle:(NSMutableParagraphStyle *)paragraphStyle font:(UIFont*)font; /** * */ - (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont*)font lineSpacing:(CGFloat)lineSpacing; /** * */ - (CGFloat)boundingRectWithSize:(CGSize)size font:(UIFont*)font lineSpacing:(CGFloat)lineSpacing maxLines:(NSInteger)maxLines; /** * */ - (BOOL)isMoreThanOneLineWithSize:(CGSize)size font:(UIFont *)font lineSpaceing:(CGFloat)lineSpacing; @end ```
/content/code_sandbox/WeChat/Category/NSString+Extension.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
173
```objective-c // // UIBarButtonItem+addition.h // TongXueBao // // Created by on 16/10/19. // #import <UIKit/UIKit.h> @interface BackView:UIView @property(nonatomic,strong)UIButton *btn; @property(nonatomic,strong)UILabel *titleLabel; @end @interface UIBarButtonItem (addition) + (UIBarButtonItem *)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action; + (UIBarButtonItem *)itemWithIcon:(NSString *)icon highIcon:(NSString *)highIcon target:(id)target action:(SEL)action; + (UIBarButtonItem *)itemWithIcon:(NSString *)icon highIcon:(NSString *)highIcon title:(NSString *)title target:(id)target action:(SEL)action; @end ```
/content/code_sandbox/WeChat/Category/UIBarButtonItem+addition.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
173
```objective-c // // UILabel+TapAction.m // WeChat // // Created by zhengwenming on 2017/9/10. // #import "UILabel+TapAction.h" #import <objc/runtime.h> #import <CoreText/CoreText.h> #import <Foundation/Foundation.h> @implementation AttributeModel @end @implementation UILabel (TapAction) #pragma mark - AssociatedObjects - (NSMutableArray *)attributeStrings { return objc_getAssociatedObject(self, _cmd); } - (void)setAttributeStrings:(NSMutableArray *)attributeStrings { objc_setAssociatedObject(self, @selector(attributeStrings), attributeStrings, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (NSMutableDictionary *)effectDic { return objc_getAssociatedObject(self, _cmd); } - (void)setEffectDic:(NSMutableDictionary *)effectDic { objc_setAssociatedObject(self, @selector(effectDic), effectDic, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (BOOL)isTapAction { return [objc_getAssociatedObject(self, _cmd) boolValue]; } - (void)setIsTapAction:(BOOL)isTapAction { objc_setAssociatedObject(self, @selector(isTapAction), @(isTapAction), OBJC_ASSOCIATION_ASSIGN); } - (void (^)(NSString *, NSRange, NSInteger))tapBlock { return objc_getAssociatedObject(self, _cmd); } - (void)setTapBlock:(void (^)(NSString *, NSRange, NSInteger))tapBlock { objc_setAssociatedObject(self, @selector(tapBlock), tapBlock, OBJC_ASSOCIATION_COPY_NONATOMIC); } - (id<TapActionDelegate>)delegate { return objc_getAssociatedObject(self, _cmd); } - (BOOL)enabledTapEffect { return [objc_getAssociatedObject(self, _cmd) boolValue]; } - (void)setEnabledTapEffect:(BOOL)enabledTapEffect { objc_setAssociatedObject(self, @selector(enabledTapEffect), @(enabledTapEffect), OBJC_ASSOCIATION_ASSIGN); self.isTapEffect = enabledTapEffect; } - (BOOL)isTapEffect { return [objc_getAssociatedObject(self, _cmd) boolValue]; } - (void)setIsTapEffect:(BOOL)isTapEffect { objc_setAssociatedObject(self, @selector(isTapEffect), @(isTapEffect), OBJC_ASSOCIATION_ASSIGN); } - (void)setDelegate:(id<TapActionDelegate>)delegate { objc_setAssociatedObject(self, @selector(delegate), delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - mainFunction - (void)tapActionWithStrings:(NSArray <NSString *> *)strings tapClicked:(void (^) (NSString *string , NSRange range , NSInteger index))tapClick { [self getRangesWithStrings:strings]; if (self.tapBlock != tapClick) { self.tapBlock = tapClick; } } - (void)tapActionWithStrings:(NSArray <NSString *> *)strings delegate:(id <TapActionDelegate> )delegate { [self getRangesWithStrings:strings]; if (self.delegate != delegate) { self.delegate = delegate; } } #pragma mark - touchAction - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { if (!self.isTapAction) { return; } if (objc_getAssociatedObject(self, @selector(enabledTapEffect))) { self.isTapEffect = self.enabledTapEffect; } UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; __weak typeof(self) weakSelf = self; [self getTapFrameWithTouchPoint:point result:^(NSString *string, NSRange range, NSInteger index) { if (weakSelf.tapBlock) { weakSelf.tapBlock (string , range , index); } if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(tapReturnString:range:index:)]) { [weakSelf.delegate tapReturnString:string range:range index:index]; } if (self.isTapEffect) { [self saveEffectDicWithRange:range]; [self tapEffectWithStatus:YES]; } }]; } - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { if (self.isTapAction) { if ([self getTapFrameWithTouchPoint:point result:nil]) { return self; } } return [super hitTest:point withEvent:event]; } #pragma mark - getTapFrame - (BOOL)getTapFrameWithTouchPoint:(CGPoint)point result:(void (^) (NSString *string , NSRange range , NSInteger index))resultBlock { CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)self.attributedText); CGMutablePathRef Path = CGPathCreateMutable(); CGPathAddRect(Path, NULL, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)); CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL); CFRange range = CTFrameGetVisibleStringRange(frame); if (self.attributedText.length > range.length) { UIFont *font ; if ([self.attributedText attribute:NSFontAttributeName atIndex:0 effectiveRange:nil]) { font = [self.attributedText attribute:NSFontAttributeName atIndex:0 effectiveRange:nil]; }else if (self.font){ font = self.font; }else { font = [UIFont systemFontOfSize:17]; } CGPathRelease(Path); Path = CGPathCreateMutable(); CGPathAddRect(Path, NULL, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height + font.lineHeight)); frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL); } CFArrayRef lines = CTFrameGetLines(frame); if (!lines) { CFRelease(frame); CFRelease(framesetter); CGPathRelease(Path); return NO; } CFIndex count = CFArrayGetCount(lines); CGPoint origins[count]; CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins); CGAffineTransform transform = [self transformForCoreText]; CGFloat verticalOffset = 0; for (CFIndex i = 0; i < count; i++) { CGPoint linePoint = origins[i]; CTLineRef line = CFArrayGetValueAtIndex(lines, i); CGRect flippedRect = [self getLineBounds:line point:linePoint]; CGRect rect = CGRectApplyAffineTransform(flippedRect, transform); rect = CGRectInset(rect, 0, 0); rect = CGRectOffset(rect, 0, verticalOffset); NSParagraphStyle *style = [self.attributedText attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:nil]; CGFloat lineSpace; if (style) { lineSpace = style.lineSpacing; }else { lineSpace = 0; } CGFloat lineOutSpace = (self.bounds.size.height - lineSpace * (count - 1) -rect.size.height * count) / 2; rect.origin.y = lineOutSpace + rect.size.height * i + lineSpace * i; if (CGRectContainsPoint(rect, point)) { CGPoint relativePoint = CGPointMake(point.x - CGRectGetMinX(rect), point.y - CGRectGetMinY(rect)); CFIndex index = CTLineGetStringIndexForPosition(line, relativePoint); CGFloat offset; CTLineGetOffsetForStringIndex(line, index, &offset); if (offset > relativePoint.x) { index = index - 1; } NSInteger link_count = self.attributeStrings.count; for (int j = 0; j < link_count; j++) { AttributeModel *model = self.attributeStrings[j]; NSRange link_range = model.range; if (NSLocationInRange(index, link_range)) { if (resultBlock) { resultBlock (model.str , model.range , (NSInteger)j); } CFRelease(frame); CFRelease(framesetter); CGPathRelease(Path); return YES; } } } } CFRelease(frame); CFRelease(framesetter); CGPathRelease(Path); return NO; } - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { if (self.isTapEffect) { [self performSelectorOnMainThread:@selector(tapEffectWithStatus:) withObject:nil waitUntilDone:NO]; } } - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { if (self.isTapEffect) { [self performSelectorOnMainThread:@selector(tapEffectWithStatus:) withObject:nil waitUntilDone:NO]; } } - (CGAffineTransform)transformForCoreText { return CGAffineTransformScale(CGAffineTransformMakeTranslation(0, self.bounds.size.height), 1.f, -1.f); } - (CGRect)getLineBounds:(CTLineRef)line point:(CGPoint)point { CGFloat ascent = 0.0f; CGFloat descent = 0.0f; CGFloat leading = 0.0f; CGFloat width = (CGFloat)CTLineGetTypographicBounds(line, &ascent, &descent, &leading); CGFloat height = ascent + fabs(descent) + leading; return CGRectMake(point.x, point.y , width, height); } #pragma mark - tapEffect - (void)tapEffectWithStatus:(BOOL)status { if (self.isTapEffect) { NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText]; NSMutableAttributedString *subAtt = [[NSMutableAttributedString alloc] initWithAttributedString:[[self.effectDic allValues] firstObject]]; NSRange range = NSRangeFromString([[self.effectDic allKeys] firstObject]); if (status) { [subAtt addAttribute:NSBackgroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, subAtt.string.length)]; [attStr replaceCharactersInRange:range withAttributedString:subAtt]; }else { [attStr replaceCharactersInRange:range withAttributedString:subAtt]; } self.attributedText = attStr; } } - (void)saveEffectDicWithRange:(NSRange)range { self.effectDic = [NSMutableDictionary dictionary]; NSAttributedString *subAttribute = [self.attributedText attributedSubstringFromRange:range]; [self.effectDic setObject:subAttribute forKey:NSStringFromRange(range)]; } #pragma mark - getRange - (void)getRangesWithStrings:(NSArray <NSString *> *)strings { if (self.attributedText == nil) { self.isTapAction = NO; return; } self.isTapAction = YES; self.isTapEffect = YES; __block NSString *totalStr = self.attributedText.string; self.attributeStrings = [NSMutableArray array]; __weak typeof(self) weakSelf = self; [strings enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { NSRange range = [totalStr rangeOfString:obj]; if (range.length != 0) { totalStr = [totalStr stringByReplacingCharactersInRange:range withString:[weakSelf getStringWithRange:range]]; AttributeModel *model = [AttributeModel new]; model.range = range; model.str = obj; [weakSelf.attributeStrings addObject:model]; } }]; } - (NSString *)getStringWithRange:(NSRange)range { NSMutableString *string = [NSMutableString string]; for (int i = 0; i < range.length ; i++) { [string appendString:@" "]; } return string; } @end ```
/content/code_sandbox/WeChat/Category/UILabel+TapAction.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,596
```objective-c // // WMCollectionViewFlowLayout.m // WMPhotoBrowser // // Created by zhengwenming on 2018/6/11. // #import "WMCollectionViewFlowLayout.h" @implementation WMCollectionViewFlowLayout - (void)prepareLayout { [super prepareLayout]; self.scrollDirection = UICollectionViewScrollDirectionHorizontal; CGSize size = self.collectionView.bounds.size; self.itemSize = CGSizeMake(size.width, size.height); self.minimumLineSpacing = 0; self.minimumInteritemSpacing = 10; } - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect { NSArray<UICollectionViewLayoutAttributes *> *layoutAttsArray = [[NSArray alloc] initWithArray:[super layoutAttributesForElementsInRect:rect] copyItems:YES]; CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width/2.0; __block CGFloat min = CGFLOAT_MAX; __block NSUInteger minIdx; [layoutAttsArray enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) { if (ABS(centerX-obj.center.x) < min) { min = ABS(centerX-obj.center.x); minIdx = index; } }]; [layoutAttsArray enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) { if (minIdx - 1 == index) { obj.center = CGPointMake(obj.center.x-self.imgaeGap, obj.center.y); } if (minIdx + 1 == index) { obj.center = CGPointMake(obj.center.x+self.imgaeGap, obj.center.y); } }]; return layoutAttsArray; } - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds { return YES; } @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/WMCollectionViewFlowLayout.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
388
```objective-c // // WMPhotoBrowserCell.h // WMPhotoBrowser // // Created by zhengwenming on 2018/1/2. // #import <UIKit/UIKit.h> #import "UIView+WMFrame.h" @interface WMPhotoBrowserCell : UICollectionViewCell @property (nonatomic, copy)NSIndexPath *currentIndexPath; @property (nonatomic, strong) UIImageView *imageView; @property (nonatomic, retain)id model; @property (nonatomic, copy) void (^singleTapGestureBlock)(void); @property (nonatomic, copy) void (^longPressGestureBlock)(WMPhotoBrowserCell *cell); @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/WMPhotoBrowserCell.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
124
```objective-c // // WMCollectionViewFlowLayout.h // WMPhotoBrowser // // Created by zhengwenming on 2018/6/11. // #import <UIKit/UIKit.h> @interface WMCollectionViewFlowLayout : UICollectionViewFlowLayout @property (nonatomic, assign) CGFloat imgaeGap; @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/WMCollectionViewFlowLayout.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
61
```objective-c // // WMPhotoBrowser.m // WMPhotoBrowser // // Created by zhengwenming on 2018/1/2. // #import "WMPhotoBrowser.h" #import "WMPhotoBrowserCell.h" #import "MBProgressHUD+Show.h" #import "WMCollectionViewFlowLayout.h" #import "UIViewController+WMExtension.h" @interface WMPhotoBrowser ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate> { } @property(nonatomic,assign)BOOL isHideNaviBar; @property(nonatomic,strong) UICollectionView *collectionView; @property(nonatomic,strong) UIPageControl *pageControl; @end @implementation WMPhotoBrowser - (BOOL)fullScreenGestureShouldBegin{ return NO; } // - (BOOL)shouldAutorotate { return NO; } // - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAllButUpsideDown; } // ViewControllerUIViewController - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return UIInterfaceOrientationPortrait; } //- (instancetype)init{ // self = [super init]; // if (self) { // if (@available(ios 11.0,*)) { // UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; // UITableView.appearance.estimatedRowHeight = 0; // UITableView.appearance.estimatedSectionFooterHeight = 0; // UITableView.appearance.estimatedSectionHeaderHeight = 0; // }else{ // if([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]){ // self.automaticallyAdjustsScrollViewInsets=NO; // } // } // } // return self; //} -(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; [self.navigationController setNavigationBarHidden:NO animated:YES]; } -(void)deleteTheImage:(UIBarButtonItem *)sender{ if (self.dataSource.count==1) { [self.dataSource removeObjectAtIndex:self.currentPhotoIndex]; [self.navigationController popViewControllerAnimated:YES]; }else{ [self.dataSource removeObjectAtIndex:self.currentPhotoIndex]; [self.collectionView reloadData]; } if (self.deleteBlock) { self.deleteBlock(self.dataSource,self.currentPhotoIndex,self.collectionView); } } -(UICollectionView *)collectionView{ if (_collectionView==nil) { WMCollectionViewFlowLayout *layout = [[WMCollectionViewFlowLayout alloc] init]; layout.imgaeGap = 20; _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width , self.view.frame.size.height) collectionViewLayout:layout]; _collectionView.backgroundColor = [UIColor blackColor]; _collectionView.dataSource = self; _collectionView.delegate = self; _collectionView.pagingEnabled = YES; _collectionView.scrollsToTop = NO; [_collectionView registerClass:[WMPhotoBrowserCell class] forCellWithReuseIdentifier:@"WMPhotoBrowserCell"]; _collectionView.showsHorizontalScrollIndicator = NO; _collectionView.contentOffset = CGPointMake(0, 0); _collectionView.contentSize = CGSizeMake(self.view.frame.size.width * self.dataSource.count, self.view.frame.size.height); } return _collectionView; } // iOS8, // == - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{ NSLog(@"size; %@", NSStringFromCGSize(size)); if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft || [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight) { NSLog(@""); self.collectionView.frame = CGRectMake(0, 0,size.width,size.height); self.pageControl.frame = CGRectMake(0, size.height-30,size.width,30); self.pageControl.centerX = self.view.centerX; }else{ self.collectionView.frame = CGRectMake(0, 0,size.width,size.height); self.pageControl.frame = CGRectMake(0, size.height-30,size.width,30); self.pageControl.centerX = self.view.centerX; } } #pragma mark #pragma mark viewDidLoad - (void)viewDidLoad { [super viewDidLoad]; if (self.downLoadNeeded) { UIButton *_saveImageBtn = [UIButton buttonWithType:UIButtonTypeCustom]; _saveImageBtn.frame = CGRectMake(0, 0, 40, 40); _saveImageBtn.autoresizingMask = UIViewAutoresizingFlexibleHeight; [_saveImageBtn setImage:[UIImage imageNamed:@"savePicture"] forState:UIControlStateNormal]; [_saveImageBtn setImage:[UIImage imageNamed:@"savePicture"] forState:UIControlStateHighlighted]; [_saveImageBtn addTarget:self action:@selector(saveImage) forControlEvents:UIControlEventTouchUpInside]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_saveImageBtn]; }else if(self.deleteNeeded){ self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteTheImage:)]; } self.view.backgroundColor = [UIColor blackColor]; self.isHideNaviBar = NO; [self.view addSubview:self.collectionView]; if (self.dataSource.count) { [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:(self.currentPhotoIndex) inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO]; } [self.view addSubview:self.pageControl]; self.pageControl.numberOfPages = self.dataSource.count; self.pageControl.currentPage = self.currentPhotoIndex; } -(UIPageControl *)pageControl{ if (!_pageControl) { CGFloat bottomOffset = 30; if (@available(iOS 11.0, *)) { BOOL isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0; if (isPhoneX) { bottomOffset = 60; } } _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-bottomOffset, self.view.frame.size.width, 30)]; _pageControl.numberOfPages = 5; _pageControl.userInteractionEnabled = NO; _pageControl.pageIndicatorTintColor = [UIColor darkGrayColor]; _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor]; _pageControl.backgroundColor = [UIColor clearColor]; } return _pageControl; } - (void)saveImage{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentPhotoIndex inSection:0]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ WMPhotoBrowserCell *currentCell = (WMPhotoBrowserCell *)[self.collectionView cellForItemAtIndexPath:indexPath]; UIImageWriteToSavedPhotosAlbum(currentCell.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil); }); }); } - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{ if (error) { [MBProgressHUD showErrorWithText:@""]; } else { [MBProgressHUD showSuccessWithText:@""]; } if (self.downLoadBlock) { self.downLoadBlock(self.dataSource,image,error); } } #pragma mark - UIScrollViewDelegate - (void)scrollViewDidScroll:(UIScrollView *)scrollView { // if (self.currentPhotoIndex==0) { // scrollView.bounces = NO; // }else{ // scrollView.bounces = YES; // } } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { if ([self.title isEqualToString:@""]) { }else{ CGPoint offSet = scrollView.contentOffset; self.currentPhotoIndex = offSet.x / self.view.width; self.pageControl.currentPage = self.currentPhotoIndex; } } #pragma mark - UICollectionViewDataSource && Delegate - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return self.dataSource.count; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { WMPhotoBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WMPhotoBrowserCell" forIndexPath:indexPath]; cell.model = self.dataSource[indexPath.row]; __weak typeof(self) weakSelf = self; if (!cell.singleTapGestureBlock) { cell.singleTapGestureBlock = ^(){ if (weakSelf.isHideNaviBar==YES) { [weakSelf.navigationController setNavigationBarHidden:NO animated:YES]; }else{ [weakSelf.navigationController setNavigationBarHidden:YES animated:YES]; } weakSelf.isHideNaviBar = !weakSelf.isHideNaviBar; [weakSelf dismissViewControllerAnimated:YES completion:^{ }]; }; } if (!cell.longPressGestureBlock) { cell.longPressGestureBlock = ^(WMPhotoBrowserCell *cell) { UIAlertController *alertAction = [UIAlertController alertControllerWithTitle:@"" message:nil preferredStyle:UIAlertControllerStyleActionSheet]; [alertAction addAction:[UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { UIImageWriteToSavedPhotosAlbum(cell.imageView.image, weakSelf, @selector(image:didFinishSavingWithError:contextInfo:), nil); }]]; [alertAction addAction:[UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { NSLog(@""); }]]; [weakSelf presentViewController:alertAction animated:YES completion:^{ }]; }; } cell.currentIndexPath = indexPath; return cell; } - (void)dealloc{ NSLog(@"%s",__FUNCTION__); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/WMPhotoBrowser.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,970
```objective-c // // WMPhotoBrowser.h // WMPhotoBrowser // // Created by zhengwenming on 2018/1/2. // #import <UIKit/UIKit.h> typedef void(^DeleteBlock)(NSMutableArray *dataSource,NSUInteger currentIndex,UICollectionView *collectionView); typedef void(^DownLoadBlock)(NSMutableArray *dataSource,UIImage *image,NSError *error); @interface WMPhotoBrowser : UIViewController /** * */ @property (nonatomic, strong) NSMutableArray *dataSource; /** * index */ @property (nonatomic, assign) NSInteger currentPhotoIndex; /** * */ @property (assign, nonatomic) BOOL downLoadNeeded; /** * */ @property (assign, nonatomic) BOOL deleteNeeded; /** * */ @property (nonatomic, copy) DownLoadBlock downLoadBlock; /** * */ @property (nonatomic, copy) DeleteBlock deleteBlock; @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/WMPhotoBrowser.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
182
```objective-c // // UIView+WMFrame.m // WMPhotoBrowser // // Created by zhengwenming on 2018/1/5. // #import "UIView+WMFrame.h" @implementation UIView (WMFrame) - (void)setX:(CGFloat)x { CGRect frame = self.frame; frame.origin.x = x; self.frame = frame; } - (CGFloat)x { return self.frame.origin.x; } - (void)setY:(CGFloat)y { CGRect frame = self.frame; frame.origin.y = y; self.frame = frame; } - (CGFloat)y { return self.frame.origin.y; } - (CGFloat)left { return self.frame.origin.x; } - (void)setLeft:(CGFloat)x { CGRect frame = self.frame; frame.origin.x = x; self.frame = frame; } - (CGFloat)top { return self.frame.origin.y; } - (void)setTop:(CGFloat)y { CGRect frame = self.frame; frame.origin.y = y; self.frame = frame; } - (CGFloat)right { return self.frame.origin.x + self.frame.size.width; } - (void)setRight:(CGFloat)right { CGRect frame = self.frame; frame.origin.x = right - frame.size.width; self.frame = frame; } - (CGFloat)bottom { return self.frame.origin.y + self.frame.size.height; } - (void)setBottom:(CGFloat)bottom { CGRect frame = self.frame; frame.origin.y = bottom - frame.size.height; self.frame = frame; } - (CGFloat)width { return self.frame.size.width; } - (void)setWidth:(CGFloat)width { CGRect frame = self.frame; frame.size.width = width; self.frame = frame; } - (CGFloat)height { return self.frame.size.height; } - (void)setHeight:(CGFloat)height { CGRect frame = self.frame; frame.size.height = height; self.frame = frame; } - (CGFloat)centerX { return self.center.x; } - (void)setCenterX:(CGFloat)centerX { self.center = CGPointMake(centerX, self.center.y); } - (CGFloat)centerY { return self.center.y; } - (void)setCenterY:(CGFloat)centerY { self.center = CGPointMake(self.center.x, centerY); } - (CGPoint)origin { return self.frame.origin; } - (void)setOrigin:(CGPoint)origin { CGRect frame = self.frame; frame.origin = origin; self.frame = frame; } - (CGSize)size { return self.frame.size; } - (void)setSize:(CGSize)size { CGRect frame = self.frame; frame.size = size; self.frame = frame; } @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/Category/UIView+WMFrame.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
588
```objective-c // // WMPhotoBrowserCell.m // WMPhotoBrowser // // Created by zhengwenming on 2018/1/2. // #import "WMPhotoBrowserCell.h" #import "UIImageView+WebCache.h" @interface WMPhotoBrowserCell ()<UIGestureRecognizerDelegate,UIScrollViewDelegate> { CGFloat _aspectRatio; } @property (nonatomic, strong) UIScrollView *scrollView; @property (nonatomic, strong) UIView *imageContainerView; @end @implementation WMPhotoBrowserCell - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor blackColor]; self.scrollView = [[UIScrollView alloc] init]; self.scrollView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height); self.scrollView.bouncesZoom = YES; self.scrollView.backgroundColor = [UIColor blackColor]; self.scrollView.maximumZoomScale = 2.5;// self.scrollView.minimumZoomScale = 1.0;// self.scrollView.multipleTouchEnabled = YES; self.scrollView.delegate = self; self.scrollView.scrollsToTop = NO; self.scrollView.showsHorizontalScrollIndicator = NO; self.scrollView.showsVerticalScrollIndicator = NO; self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; self.scrollView.delaysContentTouches = NO; self.scrollView.canCancelContentTouches = YES; self.scrollView.alwaysBounceVertical = NO; [self.contentView addSubview:self.scrollView]; self.imageContainerView = [[UIView alloc] init]; self.imageContainerView.clipsToBounds = YES; [self.scrollView addSubview:self.imageContainerView]; self.imageView = [[UIImageView alloc] init]; self.imageView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.500]; self.imageView.clipsToBounds = YES; self.imageView.userInteractionEnabled = YES; [self.imageContainerView addSubview:self.imageView]; // UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)]; [self.contentView addGestureRecognizer:singleTap]; // UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)]; doubleTap.numberOfTapsRequired = 2; [singleTap requireGestureRecognizerToFail:doubleTap]; [self.contentView addGestureRecognizer:doubleTap]; // UILongPressGestureRecognizer *longPressGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToSavePhoto:)]; [self.contentView addGestureRecognizer:longPressGes]; } return self; } -(void)longPressToSavePhoto:(UILongPressGestureRecognizer *)sender{ if (sender.state== UIGestureRecognizerStateBegan){ if (self.longPressGestureBlock) { self.longPressGestureBlock(self); } } } - (void)resizeSubviews { self.imageContainerView.origin = CGPointZero; self.imageContainerView.width = self.width; UIImage *image = self.imageView.image; if (image.size.height/image.size.width >self.height/self.width) { self.imageContainerView.height = floor(image.size.height / (image.size.width / self.width)); } else { CGFloat height = image.size.height / image.size.width * self.width; if (height < 1 || isnan(height)) height = self.height; height = floor(height); self.imageContainerView.height = height; self.imageContainerView.centerY = self.height / 2; } if (self.imageContainerView.height > self.height && self.imageContainerView.height - self.height <= 1) { self.imageContainerView.height = self.height; } self.scrollView.contentSize = CGSizeMake(self.width, MAX(self.imageContainerView.height, self.height)); [self.scrollView scrollRectToVisible:self.bounds animated:NO]; self.scrollView.alwaysBounceVertical = self.imageContainerView.height <= self.height ? NO : YES; self.imageView.frame = self.imageContainerView.bounds; } -(void)layoutSubviews{ [super layoutSubviews]; [self resizeSubviews]; } #pragma mark - UITapGestureRecognizer Event - (void)doubleTap:(UITapGestureRecognizer *)tap { if (self.scrollView.zoomScale > 1.0) { [self.scrollView setZoomScale:1.0 animated:YES]; } else { CGPoint touchPoint = [tap locationInView:self.imageView]; CGFloat newZoomScale = self.scrollView.maximumZoomScale; CGFloat xsize = self.frame.size.width / newZoomScale; CGFloat ysize = self.frame.size.height / newZoomScale; [self.scrollView zoomToRect:CGRectMake(touchPoint.x - xsize/2, touchPoint.y - ysize/2, xsize, ysize) animated:YES]; } } - (void)setModel:(id )model { _model = model; [self.scrollView setZoomScale:1.0 animated:NO]; if ([model isKindOfClass:[UIImage class]]){ UIImage *aImage = (UIImage *)model; self.imageView.image = aImage; }else if ([model isKindOfClass:[NSString class]]){ NSString *aString = (NSString *)model; if ([aString rangeOfString:@"http"].location!=NSNotFound) { [self.imageView sd_setImageWithURL:[NSURL URLWithString:aString] placeholderImage:[UIImage imageNamed:@"placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { [self resizeSubviews]; }]; }else{ self.imageView.image = [UIImage imageNamed:aString]; } }else if ([model isKindOfClass:[NSURL class]]){ NSURL *aURL = (NSURL *)model; [self.imageView sd_setImageWithURL:aURL placeholderImage:[UIImage imageNamed:@"placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { [self resizeSubviews]; }]; } // else if ([model isKindOfClass:[IMAMsg class]]){ // IMAMsg *aImageMsg = (IMAMsg *)model; // TIMImageElem *elem = (TIMImageElem *)[aImageMsg.msg getElem:0]; // [elem asyncThumbImage:^(NSString *path, UIImage *image, BOOL succ, BOOL isAsync) { // if ([path containsString:@"http"]) { // [self.imageView sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:@"ablePlaceHolder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { // [self resizeSubviews]; // }]; // } // // } inMsg:aImageMsg]; // } [self resizeSubviews]; } - (void)singleTap:(UITapGestureRecognizer *)tap { if (self.singleTapGestureBlock) { self.singleTapGestureBlock(); } } #pragma mark - UIScrollViewDelegate - (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return self.imageContainerView; } - (void)scrollViewDidZoom:(UIScrollView *)scrollView { CGFloat offsetX = (scrollView.width > scrollView.contentSize.width) ? (scrollView.width - scrollView.contentSize.width) * 0.5 : 0.0; CGFloat offsetY = (scrollView.height > scrollView.contentSize.height) ? (scrollView.height - scrollView.contentSize.height) * 0.5 : 0.0; self.imageContainerView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, scrollView.contentSize.height * 0.5 + offsetY); } -(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{ return YES; } - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { if (self.scrollView.contentOffset.x <= 0) { if ([otherGestureRecognizer.delegate isKindOfClass:NSClassFromString(@"_FDFullscreenPopGestureRecognizerDelegate")]) { return YES; } } return NO; } @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/WMPhotoBrowserCell.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,670
```objective-c // // UIView+WMFrame.h // WMPhotoBrowser // // Created by zhengwenming on 2018/1/5. // #import <UIKit/UIKit.h> @interface UIView (WMFrame) @property (nonatomic, assign) CGFloat x; @property (nonatomic, assign) CGFloat y; @property (nonatomic) CGFloat left; ///< Shortcut for frame.origin.x. @property (nonatomic) CGFloat top; ///< Shortcut for frame.origin.y @property (nonatomic) CGFloat right; ///< Shortcut for frame.origin.x + frame.size.width @property (nonatomic) CGFloat bottom; ///< Shortcut for frame.origin.y + frame.size.height @property (nonatomic) CGFloat width; ///< Shortcut for frame.size.width. @property (nonatomic) CGFloat height; ///< Shortcut for frame.size.height. @property (nonatomic) CGFloat centerX; ///< Shortcut for center.x @property (nonatomic) CGFloat centerY; ///< Shortcut for center.y @property (nonatomic) CGPoint origin; ///< Shortcut for frame.origin. @property (nonatomic) CGSize size; ///< Shortcut for frame.size. @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/Category/UIView+WMFrame.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
222
```objective-c // // UIViewController+WMExtension.h // WMPhotoBrowser // // Created by zhengwenming on 2018/6/14. // #import <UIKit/UIKit.h> typedef void(^PopBlock)(UIBarButtonItem *backItem); @interface UIViewController (WMExtension) @property(nonatomic,copy)PopBlock popBlock; @property (nonatomic, assign) BOOL isHideBackItem; //YES - (BOOL)fullScreenGestureShouldBegin; /** @return */ -(NSString *)backIconName; @end @interface UITabBarController (WMExtension) @end @interface UINavigationController (WMExtension)<UIGestureRecognizerDelegate> @end @interface UIAlertController (WMExtension) @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/Category/UIViewController+WMExtension.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
138
```objective-c // // UIViewController+WMExtension.m // WMPhotoBrowser // // Created by zhengwenming on 2018/6/14. // #import "UIViewController+WMExtension.h" #import <objc/runtime.h> @implementation UIViewController (WMExtension) -(PopBlock)popBlock{ return objc_getAssociatedObject(self, _cmd); } -(void)setPopBlock:(PopBlock)popBlock{ objc_setAssociatedObject(self, @selector(popBlock), popBlock, OBJC_ASSOCIATION_COPY_NONATOMIC); } -(BOOL)isHideBackItem{ return [objc_getAssociatedObject(self, _cmd) boolValue]; } -(void)setIsHideBackItem:(BOOL)isHideBackItem{ objc_setAssociatedObject(self, @selector(isHideBackItem), @(isHideBackItem), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } //YES - (BOOL)fullScreenGestureShouldBegin{ return YES; } //#warning //,arrows_black, -(NSString *)backIconName{ return @"arrows_black"; } // - (BOOL)shouldAutorotate { return NO; } // - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } // ViewControllerUIViewController - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return UIInterfaceOrientationPortrait; } - (UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleDefault; } - (BOOL)prefersStatusBarHidden { return NO; } @end @implementation UITabBarController (WMExtension) + (void)load { SEL selectors[] = { @selector(selectedIndex) }; for (NSUInteger index = 0; index < sizeof(selectors) / sizeof(SEL); ++index) { SEL originalSelector = selectors[index]; SEL swizzledSelector = NSSelectorFromString([@"wm_" stringByAppendingString:NSStringFromSelector(originalSelector)]); Method originalMethod = class_getInstanceMethod(self, originalSelector); Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector); if (class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))) { class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, swizzledMethod); } } } - (NSInteger)wm_selectedIndex { NSInteger index = [self wm_selectedIndex]; if (index > self.viewControllers.count){ return 0; } return index; } // - (BOOL)shouldAutorotate { UIViewController *vc = self.viewControllers[self.selectedIndex]; if ([vc isKindOfClass:UINavigationController.class]) { UINavigationController *nav = (UINavigationController *)vc; return [nav.topViewController shouldAutorotate]; } else { return [vc shouldAutorotate]; } } // - (UIInterfaceOrientationMask)supportedInterfaceOrientations { UIViewController *vc = self.viewControllers[self.selectedIndex]; if ([vc isKindOfClass:UINavigationController.class]) { UINavigationController *nav = (UINavigationController *)vc; return [nav.topViewController supportedInterfaceOrientations]; } else { return [vc supportedInterfaceOrientations]; } } // ViewControllerUIViewController - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { UIViewController *vc = self.viewControllers[self.selectedIndex]; if ([vc isKindOfClass:UINavigationController.class]) { UINavigationController *nav = (UINavigationController *)vc; return [nav.topViewController preferredInterfaceOrientationForPresentation]; } else { return [vc preferredInterfaceOrientationForPresentation]; } } @end @implementation UINavigationController (WMExtension) // - (BOOL)shouldAutorotate { return [self.topViewController shouldAutorotate]; } // - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return [self.topViewController supportedInterfaceOrientations]; } // ViewControllerUIViewController - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return [self.topViewController preferredInterfaceOrientationForPresentation]; } - (UIViewController *)childViewControllerForStatusBarStyle { return self.topViewController; } - (UIViewController *)childViewControllerForStatusBarHidden { return self.topViewController; } @end @implementation UIAlertController (WMExtension) #if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000 - (NSUInteger)supportedInterfaceOrientations; { return UIInterfaceOrientationMaskAll; } #else - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAll; } #endif @end ```
/content/code_sandbox/WeChat/ThirdLib/WMPhotoBrowser/Category/UIViewController+WMExtension.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
947
```objective-c // : path_to_url // : path_to_url // UIScrollView+Extension.m // MJRefreshExample // // Created by MJ Lee on 14-5-28. // #import "UIScrollView+MJExtension.h" #import <objc/runtime.h> @implementation UIScrollView (MJExtension) - (void)setMj_insetT:(CGFloat)mj_insetT { UIEdgeInsets inset = self.contentInset; inset.top = mj_insetT; self.contentInset = inset; } - (CGFloat)mj_insetT { return self.contentInset.top; } - (void)setMj_insetB:(CGFloat)mj_insetB { UIEdgeInsets inset = self.contentInset; inset.bottom = mj_insetB; self.contentInset = inset; } - (CGFloat)mj_insetB { return self.contentInset.bottom; } - (void)setMj_insetL:(CGFloat)mj_insetL { UIEdgeInsets inset = self.contentInset; inset.left = mj_insetL; self.contentInset = inset; } - (CGFloat)mj_insetL { return self.contentInset.left; } - (void)setMj_insetR:(CGFloat)mj_insetR { UIEdgeInsets inset = self.contentInset; inset.right = mj_insetR; self.contentInset = inset; } - (CGFloat)mj_insetR { return self.contentInset.right; } - (void)setMj_offsetX:(CGFloat)mj_offsetX { CGPoint offset = self.contentOffset; offset.x = mj_offsetX; self.contentOffset = offset; } - (CGFloat)mj_offsetX { return self.contentOffset.x; } - (void)setMj_offsetY:(CGFloat)mj_offsetY { CGPoint offset = self.contentOffset; offset.y = mj_offsetY; self.contentOffset = offset; } - (CGFloat)mj_offsetY { return self.contentOffset.y; } - (void)setMj_contentW:(CGFloat)mj_contentW { CGSize size = self.contentSize; size.width = mj_contentW; self.contentSize = size; } - (CGFloat)mj_contentW { return self.contentSize.width; } - (void)setMj_contentH:(CGFloat)mj_contentH { CGSize size = self.contentSize; size.height = mj_contentH; self.contentSize = size; } - (CGFloat)mj_contentH { return self.contentSize.height; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/UIScrollView+MJExtension.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
526
```objective-c // : path_to_url // : path_to_url // UIScrollView+MJRefresh.h // MJRefreshExample // // Created by MJ Lee on 15/3/4. // ScrollView #import <UIKit/UIKit.h> #import "MJRefreshConst.h" @class MJRefreshHeader, MJRefreshFooter; @interface UIScrollView (MJRefresh) /** */ @property (strong, nonatomic) MJRefreshHeader *mj_header; @property (strong, nonatomic) MJRefreshHeader *header MJRefreshDeprecated("mj_header"); /** */ @property (strong, nonatomic) MJRefreshFooter *mj_footer; @property (strong, nonatomic) MJRefreshFooter *footer MJRefreshDeprecated("mj_footer"); #pragma mark - other - (NSInteger)mj_totalDataCount; @property (copy, nonatomic) void (^mj_reloadDataBlock)(NSInteger totalDataCount); @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/UIScrollView+MJRefresh.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
178
```objective-c // : path_to_url // : path_to_url // UIScrollView+Extension.h // MJRefreshExample // // Created by MJ Lee on 14-5-28. // #import <UIKit/UIKit.h> @interface UIScrollView (MJExtension) @property (assign, nonatomic) CGFloat mj_insetT; @property (assign, nonatomic) CGFloat mj_insetB; @property (assign, nonatomic) CGFloat mj_insetL; @property (assign, nonatomic) CGFloat mj_insetR; @property (assign, nonatomic) CGFloat mj_offsetX; @property (assign, nonatomic) CGFloat mj_offsetY; @property (assign, nonatomic) CGFloat mj_contentW; @property (assign, nonatomic) CGFloat mj_contentH; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/UIScrollView+MJExtension.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
150
```objective-c // : path_to_url // : path_to_url #import "UIScrollView+MJRefresh.h" #import "UIScrollView+MJExtension.h" #import "UIView+MJExtension.h" #import "MJRefreshNormalHeader.h" #import "MJRefreshGifHeader.h" #import "MJRefreshBackNormalFooter.h" #import "MJRefreshBackGifFooter.h" #import "MJRefreshAutoNormalFooter.h" #import "MJRefreshAutoGifFooter.h" ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/MJRefresh.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
94
```objective-c // : path_to_url // : path_to_url // UIView+Extension.h // MJRefreshExample // // Created by MJ Lee on 14-5-28. // #import <UIKit/UIKit.h> @interface UIView (MJExtension) @property (assign, nonatomic) CGFloat mj_x; @property (assign, nonatomic) CGFloat mj_y; @property (assign, nonatomic) CGFloat mj_w; @property (assign, nonatomic) CGFloat mj_h; @property (assign, nonatomic) CGSize mj_size; @property (assign, nonatomic) CGPoint mj_origin; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/UIView+MJExtension.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
116
```objective-c // : path_to_url // : path_to_url #import <UIKit/UIKit.h> #import <objc/message.h> // #define MJWeakSelf __weak typeof(self) weakSelf = self; // #ifdef DEBUG #define MJRefreshLog(...) NSLog(__VA_ARGS__) #else #define MJRefreshLog(...) #endif // #define MJRefreshDeprecated(instead) NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, instead) // objc_msgSend #define MJRefreshMsgSend(...) ((void (*)(void *, SEL, UIView *))objc_msgSend)(__VA_ARGS__) #define MJRefreshMsgTarget(target) (__bridge void *)(target) // RGB #define MJRefreshColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0] // #define MJRefreshLabelTextColor MJRefreshColor(90, 90, 90) // #define MJRefreshLabelFont [UIFont boldSystemFontOfSize:14] // #define MJRefreshSrcName(file) [@"MJRefresh.bundle" stringByAppendingPathComponent:file] #define MJRefreshFrameworkSrcName(file) [@"Frameworks/MJRefresh.framework/MJRefresh.bundle" stringByAppendingPathComponent:file] // UIKIT_EXTERN const CGFloat MJRefreshHeaderHeight; UIKIT_EXTERN const CGFloat MJRefreshFooterHeight; UIKIT_EXTERN const CGFloat MJRefreshFastAnimationDuration; UIKIT_EXTERN const CGFloat MJRefreshSlowAnimationDuration; UIKIT_EXTERN NSString *const MJRefreshKeyPathContentOffset; UIKIT_EXTERN NSString *const MJRefreshKeyPathContentSize; UIKIT_EXTERN NSString *const MJRefreshKeyPathContentInset; UIKIT_EXTERN NSString *const MJRefreshKeyPathPanState; UIKIT_EXTERN NSString *const MJRefreshHeaderLastUpdatedTimeKey; UIKIT_EXTERN NSString *const MJRefreshHeaderIdleText; UIKIT_EXTERN NSString *const MJRefreshHeaderPullingText; UIKIT_EXTERN NSString *const MJRefreshHeaderRefreshingText; UIKIT_EXTERN NSString *const MJRefreshAutoFooterIdleText; UIKIT_EXTERN NSString *const MJRefreshAutoFooterRefreshingText; UIKIT_EXTERN NSString *const MJRefreshAutoFooterNoMoreDataText; UIKIT_EXTERN NSString *const MJRefreshBackFooterIdleText; UIKIT_EXTERN NSString *const MJRefreshBackFooterPullingText; UIKIT_EXTERN NSString *const MJRefreshBackFooterRefreshingText; UIKIT_EXTERN NSString *const MJRefreshBackFooterNoMoreDataText; // #define MJRefreshCheckState \ MJRefreshState oldState = self.state; \ if (state == oldState) return; \ [super setState:state]; ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/MJRefreshConst.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
536
```objective-c // : path_to_url // : path_to_url // UIScrollView+MJRefresh.m // MJRefreshExample // // Created by MJ Lee on 15/3/4. // #import "UIScrollView+MJRefresh.h" #import "MJRefreshHeader.h" #import "MJRefreshFooter.h" #import <objc/runtime.h> @implementation NSObject (MJRefresh) + (void)exchangeInstanceMethod1:(SEL)method1 method2:(SEL)method2 { method_exchangeImplementations(class_getInstanceMethod(self, method1), class_getInstanceMethod(self, method2)); } + (void)exchangeClassMethod1:(SEL)method1 method2:(SEL)method2 { method_exchangeImplementations(class_getClassMethod(self, method1), class_getClassMethod(self, method2)); } @end @implementation UIScrollView (MJRefresh) #pragma mark - header static const char MJRefreshHeaderKey = '\0'; - (void)setMj_header:(MJRefreshHeader *)mj_header { if (mj_header != self.mj_header) { // [self.mj_header removeFromSuperview]; [self insertSubview:mj_header atIndex:0]; // [self willChangeValueForKey:@"mj_header"]; // KVO objc_setAssociatedObject(self, &MJRefreshHeaderKey, mj_header, OBJC_ASSOCIATION_ASSIGN); [self didChangeValueForKey:@"mj_header"]; // KVO } } - (MJRefreshHeader *)mj_header { return objc_getAssociatedObject(self, &MJRefreshHeaderKey); } #pragma mark - footer static const char MJRefreshFooterKey = '\0'; - (void)setMj_footer:(MJRefreshFooter *)mj_footer { if (mj_footer != self.mj_footer) { // [self.mj_footer removeFromSuperview]; [self addSubview:mj_footer]; // [self willChangeValueForKey:@"mj_footer"]; // KVO objc_setAssociatedObject(self, &MJRefreshFooterKey, mj_footer, OBJC_ASSOCIATION_ASSIGN); [self didChangeValueForKey:@"mj_footer"]; // KVO } } - (MJRefreshFooter *)mj_footer { return objc_getAssociatedObject(self, &MJRefreshFooterKey); } #pragma mark - - (void)setFooter:(MJRefreshFooter *)footer { self.mj_footer = footer; } - (MJRefreshFooter *)footer { return self.mj_footer; } - (void)setHeader:(MJRefreshHeader *)header { self.mj_header = header; } - (MJRefreshHeader *)header { return self.mj_header; } #pragma mark - other - (NSInteger)mj_totalDataCount { NSInteger totalCount = 0; if ([self isKindOfClass:[UITableView class]]) { UITableView *tableView = (UITableView *)self; for (NSInteger section = 0; section<tableView.numberOfSections; section++) { totalCount += [tableView numberOfRowsInSection:section]; } } else if ([self isKindOfClass:[UICollectionView class]]) { UICollectionView *collectionView = (UICollectionView *)self; for (NSInteger section = 0; section<collectionView.numberOfSections; section++) { totalCount += [collectionView numberOfItemsInSection:section]; } } return totalCount; } static const char MJRefreshReloadDataBlockKey = '\0'; - (void)setMj_reloadDataBlock:(void (^)(NSInteger))mj_reloadDataBlock { [self willChangeValueForKey:@"mj_reloadDataBlock"]; // KVO objc_setAssociatedObject(self, &MJRefreshReloadDataBlockKey, mj_reloadDataBlock, OBJC_ASSOCIATION_COPY_NONATOMIC); [self didChangeValueForKey:@"mj_reloadDataBlock"]; // KVO } - (void (^)(NSInteger))mj_reloadDataBlock { return objc_getAssociatedObject(self, &MJRefreshReloadDataBlockKey); } - (void)executeReloadDataBlock { !self.mj_reloadDataBlock ? : self.mj_reloadDataBlock(self.mj_totalDataCount); } @end @implementation UITableView (MJRefresh) + (void)load { [self exchangeInstanceMethod1:@selector(reloadData) method2:@selector(mj_reloadData)]; } - (void)mj_reloadData { [self mj_reloadData]; [self executeReloadDataBlock]; } @end @implementation UICollectionView (MJRefresh) + (void)load { [self exchangeInstanceMethod1:@selector(reloadData) method2:@selector(mj_reloadData)]; } - (void)mj_reloadData { [self mj_reloadData]; [self executeReloadDataBlock]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/UIScrollView+MJRefresh.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
976
```objective-c // : path_to_url // : path_to_url #import <UIKit/UIKit.h> const CGFloat MJRefreshHeaderHeight = 54.0; const CGFloat MJRefreshFooterHeight = 44.0; const CGFloat MJRefreshFastAnimationDuration = 0.25; const CGFloat MJRefreshSlowAnimationDuration = 0.4; NSString *const MJRefreshKeyPathContentOffset = @"contentOffset"; NSString *const MJRefreshKeyPathContentInset = @"contentInset"; NSString *const MJRefreshKeyPathContentSize = @"contentSize"; NSString *const MJRefreshKeyPathPanState = @"state"; NSString *const MJRefreshHeaderLastUpdatedTimeKey = @"MJRefreshHeaderLastUpdatedTimeKey"; NSString *const MJRefreshHeaderIdleText = @""; NSString *const MJRefreshHeaderPullingText = @""; NSString *const MJRefreshHeaderRefreshingText = @"..."; NSString *const MJRefreshAutoFooterIdleText = @""; NSString *const MJRefreshAutoFooterRefreshingText = @"..."; NSString *const MJRefreshAutoFooterNoMoreDataText = @""; NSString *const MJRefreshBackFooterIdleText = @""; NSString *const MJRefreshBackFooterPullingText = @""; NSString *const MJRefreshBackFooterRefreshingText = @"..."; NSString *const MJRefreshBackFooterNoMoreDataText = @""; ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/MJRefreshConst.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
266
```objective-c // : path_to_url // : path_to_url // UIView+Extension.m // MJRefreshExample // // Created by MJ Lee on 14-5-28. // #import "UIView+MJExtension.h" @implementation UIView (MJExtension) - (void)setMj_x:(CGFloat)mj_x { CGRect frame = self.frame; frame.origin.x = mj_x; self.frame = frame; } - (CGFloat)mj_x { return self.frame.origin.x; } - (void)setMj_y:(CGFloat)mj_y { CGRect frame = self.frame; frame.origin.y = mj_y; self.frame = frame; } - (CGFloat)mj_y { return self.frame.origin.y; } - (void)setMj_w:(CGFloat)mj_w { CGRect frame = self.frame; frame.size.width = mj_w; self.frame = frame; } - (CGFloat)mj_w { return self.frame.size.width; } - (void)setMj_h:(CGFloat)mj_h { CGRect frame = self.frame; frame.size.height = mj_h; self.frame = frame; } - (CGFloat)mj_h { return self.frame.size.height; } - (void)setMj_size:(CGSize)mj_size { CGRect frame = self.frame; frame.size = mj_size; self.frame = frame; } - (CGSize)mj_size { return self.frame.size; } - (void)setMj_origin:(CGPoint)mj_origin { CGRect frame = self.frame; frame.origin = mj_origin; self.frame = frame; } - (CGPoint)mj_origin { return self.frame.origin; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/UIView+MJExtension.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
368
```objective-c // // MJRefreshAutoFooter.m // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshAutoFooter.h" @interface MJRefreshAutoFooter() @end @implementation MJRefreshAutoFooter #pragma mark - - (void)willMoveToSuperview:(UIView *)newSuperview { [super willMoveToSuperview:newSuperview]; if (newSuperview) { // if (self.hidden == NO) { self.scrollView.mj_insetB += self.mj_h; } // self.mj_y = _scrollView.mj_contentH; } else { // if (self.hidden == NO) { self.scrollView.mj_insetB -= self.mj_h; } } } #pragma mark - - (void)setAppearencePercentTriggerAutoRefresh:(CGFloat)appearencePercentTriggerAutoRefresh { self.triggerAutomaticallyRefreshPercent = appearencePercentTriggerAutoRefresh; } - (CGFloat)appearencePercentTriggerAutoRefresh { return self.triggerAutomaticallyRefreshPercent; } #pragma mark - - (void)prepare { [super prepare]; // 100% self.triggerAutomaticallyRefreshPercent = 1.0; // self.automaticallyRefresh = YES; } - (void)scrollViewContentSizeDidChange:(NSDictionary *)change { [super scrollViewContentSizeDidChange:change]; // self.mj_y = self.scrollView.mj_contentH; } - (void)scrollViewContentOffsetDidChange:(NSDictionary *)change { [super scrollViewContentOffsetDidChange:change]; if (self.state != MJRefreshStateIdle || !self.automaticallyRefresh || self.mj_y == 0) return; if (_scrollView.mj_insetT + _scrollView.mj_contentH > _scrollView.mj_h) { // // _scrollView.mj_contentHself.mj_y if (_scrollView.mj_offsetY >= _scrollView.mj_contentH - _scrollView.mj_h + self.mj_h * self.triggerAutomaticallyRefreshPercent + _scrollView.mj_insetB - self.mj_h) { // CGPoint old = [change[@"old"] CGPointValue]; CGPoint new = [change[@"new"] CGPointValue]; if (new.y <= old.y) return; // [self beginRefreshing]; } } } - (void)scrollViewPanStateDidChange:(NSDictionary *)change { [super scrollViewPanStateDidChange:change]; if (self.state != MJRefreshStateIdle) return; if (_scrollView.panGestureRecognizer.state == UIGestureRecognizerStateEnded) {// if (_scrollView.mj_insetT + _scrollView.mj_contentH <= _scrollView.mj_h) { // if (_scrollView.mj_offsetY >= - _scrollView.mj_insetT) { // [self beginRefreshing]; } } else { // if (_scrollView.mj_offsetY >= _scrollView.mj_contentH + _scrollView.mj_insetB - _scrollView.mj_h) { [self beginRefreshing]; } } } } - (void)setState:(MJRefreshState)state { MJRefreshCheckState if (state == MJRefreshStateRefreshing) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self executeRefreshingCallback]; }); } } - (void)setHidden:(BOOL)hidden { BOOL lastHidden = self.isHidden; [super setHidden:hidden]; if (!lastHidden && hidden) { self.state = MJRefreshStateIdle; self.scrollView.mj_insetB -= self.mj_h; } else if (lastHidden && !hidden) { self.scrollView.mj_insetB += self.mj_h; // self.mj_y = _scrollView.mj_contentH; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshAutoFooter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
819
```objective-c // : path_to_url // : path_to_url // MJRefreshComponent.h // MJRefreshExample // // Created by MJ Lee on 15/3/4. // #import <UIKit/UIKit.h> #import "MJRefreshConst.h" #import "UIView+MJExtension.h" #import "UIScrollView+MJExtension.h" #import "UIScrollView+MJRefresh.h" /** */ typedef NS_ENUM(NSInteger, MJRefreshState) { /** */ MJRefreshStateIdle = 1, /** */ MJRefreshStatePulling, /** */ MJRefreshStateRefreshing, /** */ MJRefreshStateWillRefresh, /** */ MJRefreshStateNoMoreData }; /** */ typedef void (^MJRefreshComponentRefreshingBlock)(); /** */ @interface MJRefreshComponent : UIView { /** scrollViewinset */ UIEdgeInsets _scrollViewOriginalInset; /** */ __weak UIScrollView *_scrollView; } #pragma mark - /** */ @property (copy, nonatomic) MJRefreshComponentRefreshingBlock refreshingBlock; /** */ - (void)setRefreshingTarget:(id)target refreshingAction:(SEL)action; /** */ @property (weak, nonatomic) id refreshingTarget; /** */ @property (assign, nonatomic) SEL refreshingAction; /** */ - (void)executeRefreshingCallback; #pragma mark - /** */ - (void)beginRefreshing; /** */ - (void)endRefreshing; /** */ - (BOOL)isRefreshing; /** */ @property (assign, nonatomic) MJRefreshState state; #pragma mark - /** scrollViewinset */ @property (assign, nonatomic, readonly) UIEdgeInsets scrollViewOriginalInset; /** */ @property (weak, nonatomic, readonly) UIScrollView *scrollView; #pragma mark - /** */ - (void)prepare NS_REQUIRES_SUPER; /** frame */ - (void)placeSubviews NS_REQUIRES_SUPER; /** scrollViewcontentOffset */ - (void)scrollViewContentOffsetDidChange:(NSDictionary *)change NS_REQUIRES_SUPER; /** scrollViewcontentSize */ - (void)scrollViewContentSizeDidChange:(NSDictionary *)change NS_REQUIRES_SUPER; /** scrollView */ - (void)scrollViewPanStateDidChange:(NSDictionary *)change NS_REQUIRES_SUPER; #pragma mark - /** () */ @property (assign, nonatomic) CGFloat pullingPercent; /** */ @property (assign, nonatomic, getter=isAutoChangeAlpha) BOOL autoChangeAlpha MJRefreshDeprecated("automaticallyChangeAlpha"); /** */ @property (assign, nonatomic, getter=isAutomaticallyChangeAlpha) BOOL automaticallyChangeAlpha; @end @interface UILabel(MJRefresh) + (instancetype)label; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshComponent.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
541
```objective-c // : path_to_url // : path_to_url // MJRefreshFooter.h // MJRefreshExample // // Created by MJ Lee on 15/3/5. // #import "MJRefreshComponent.h" @interface MJRefreshFooter : MJRefreshComponent /** footer */ + (instancetype)footerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock; /** footer */ + (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; /** */ - (void)endRefreshingWithNoMoreData; - (void)noticeNoMoreData MJRefreshDeprecated("endRefreshingWithNoMoreData"); /** */ - (void)resetNoMoreData; /** scrollViewcontentInsetbottom */ @property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetBottom; /** */ @property (assign, nonatomic, getter=isAutomaticallyHidden) BOOL automaticallyHidden; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshFooter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
190
```objective-c // : path_to_url // : path_to_url // MJRefreshFooter.m // MJRefreshExample // // Created by MJ Lee on 15/3/5. // #import "MJRefreshFooter.h" @interface MJRefreshFooter() @end @implementation MJRefreshFooter #pragma mark - + (instancetype)footerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock { MJRefreshFooter *cmp = [[self alloc] init]; cmp.refreshingBlock = refreshingBlock; return cmp; } + (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action { MJRefreshFooter *cmp = [[self alloc] init]; [cmp setRefreshingTarget:target refreshingAction:action]; return cmp; } #pragma mark - - (void)prepare { [super prepare]; // self.mj_h = MJRefreshFooterHeight; // self.automaticallyHidden = YES; } - (void)willMoveToSuperview:(UIView *)newSuperview { [super willMoveToSuperview:newSuperview]; if (newSuperview) { // scrollView if ([self.scrollView isKindOfClass:[UITableView class]] || [self.scrollView isKindOfClass:[UICollectionView class]]) { [self.scrollView setMj_reloadDataBlock:^(NSInteger totalDataCount) { if (self.isAutomaticallyHidden) { self.hidden = (totalDataCount == 0); } }]; } } } #pragma mark - - (void)endRefreshingWithNoMoreData { self.state = MJRefreshStateNoMoreData; } - (void)noticeNoMoreData { [self endRefreshingWithNoMoreData]; } - (void)resetNoMoreData { self.state = MJRefreshStateIdle; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshFooter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
384
```objective-c // : path_to_url // : path_to_url // MJRefreshHeader.h // MJRefreshExample // // Created by MJ Lee on 15/3/4. // : #import "MJRefreshComponent.h" @interface MJRefreshHeader : MJRefreshComponent /** header */ + (instancetype)headerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock; /** header */ + (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; /** key */ @property (copy, nonatomic) NSString *lastUpdatedTimeKey; /** */ @property (strong, nonatomic, readonly) NSDate *lastUpdatedTime; /** scrollViewcontentInsettop */ @property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetTop; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshHeader.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
160
```objective-c // // MJRefreshAutoFooter.h // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshFooter.h" @interface MJRefreshAutoFooter : MJRefreshFooter /** (YES) */ @property (assign, nonatomic, getter=isAutomaticallyRefresh) BOOL automaticallyRefresh; /** (1.0) */ @property (assign, nonatomic) CGFloat appearencePercentTriggerAutoRefresh MJRefreshDeprecated("automaticallyChangeAlpha"); /** (1.0) */ @property (assign, nonatomic) CGFloat triggerAutomaticallyRefreshPercent; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshAutoFooter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
121
```objective-c // // MJRefreshBackFooter.m // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshBackFooter.h" @interface MJRefreshBackFooter() @property (assign, nonatomic) NSInteger lastRefreshCount; @property (assign, nonatomic) CGFloat lastBottomDelta; @end @implementation MJRefreshBackFooter #pragma mark - - (void)willMoveToSuperview:(UIView *)newSuperview { [super willMoveToSuperview:newSuperview]; [self scrollViewContentSizeDidChange:nil]; } #pragma mark - - (void)scrollViewContentOffsetDidChange:(NSDictionary *)change { [super scrollViewContentOffsetDidChange:change]; // if (self.state == MJRefreshStateRefreshing) return; _scrollViewOriginalInset = self.scrollView.contentInset; // contentOffset CGFloat currentOffsetY = self.scrollView.mj_offsetY; // offsetY CGFloat happenOffsetY = [self happenOffsetY]; // if (currentOffsetY <= happenOffsetY) return; CGFloat pullingPercent = (currentOffsetY - happenOffsetY) / self.mj_h; // pullingPercent if (self.state == MJRefreshStateNoMoreData) { self.pullingPercent = pullingPercent; return; } if (self.scrollView.isDragging) { self.pullingPercent = pullingPercent; // CGFloat normal2pullingOffsetY = happenOffsetY + self.mj_h; if (self.state == MJRefreshStateIdle && currentOffsetY > normal2pullingOffsetY) { // self.state = MJRefreshStatePulling; } else if (self.state == MJRefreshStatePulling && currentOffsetY <= normal2pullingOffsetY) { // self.state = MJRefreshStateIdle; } } else if (self.state == MJRefreshStatePulling) {// && // [self beginRefreshing]; } else if (pullingPercent < 1) { self.pullingPercent = pullingPercent; } } - (void)scrollViewContentSizeDidChange:(NSDictionary *)change { [super scrollViewContentSizeDidChange:change]; // CGFloat contentHeight = self.scrollView.mj_contentH + self.ignoredScrollViewContentInsetBottom; // CGFloat scrollHeight = self.scrollView.mj_h - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom + self.ignoredScrollViewContentInsetBottom; // self.mj_y = MAX(contentHeight, scrollHeight); } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { // if (MJRefreshStateRefreshing == oldState) { [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{ self.scrollView.mj_insetB -= self.lastBottomDelta; // if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0; } completion:^(BOOL finished) { self.pullingPercent = 0.0; }]; } CGFloat deltaH = [self heightForContentBreakView]; // if (MJRefreshStateRefreshing == oldState && deltaH > 0 && self.scrollView.mj_totalDataCount != self.lastRefreshCount) { self.scrollView.mj_offsetY = self.scrollView.mj_offsetY; } } else if (state == MJRefreshStateRefreshing) { // self.lastRefreshCount = self.scrollView.mj_totalDataCount; [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ CGFloat bottom = self.mj_h + self.scrollViewOriginalInset.bottom; CGFloat deltaH = [self heightForContentBreakView]; if (deltaH < 0) { // view bottom -= deltaH; } self.lastBottomDelta = bottom - self.scrollView.mj_insetB; self.scrollView.mj_insetB = bottom; self.scrollView.mj_offsetY = [self happenOffsetY] + self.mj_h; } completion:^(BOOL finished) { [self executeRefreshingCallback]; }]; } } #pragma mark - - (void)endRefreshing { if ([self.scrollView isKindOfClass:[UICollectionView class]]) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [super endRefreshing]; }); } else { [super endRefreshing]; } } - (void)noticeNoMoreData { if ([self.scrollView isKindOfClass:[UICollectionView class]]) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [super noticeNoMoreData]; }); } else { [super noticeNoMoreData]; } } #pragma mark - #pragma mark scrollView view - (CGFloat)heightForContentBreakView { CGFloat h = self.scrollView.frame.size.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top; return self.scrollView.contentSize.height - h; } #pragma mark contentOffset.y - (CGFloat)happenOffsetY { CGFloat deltaH = [self heightForContentBreakView]; if (deltaH > 0) { return deltaH - self.scrollViewOriginalInset.top; } else { return - self.scrollViewOriginalInset.top; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshBackFooter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,148
```objective-c // // MJRefreshBackFooter.h // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshFooter.h" @interface MJRefreshBackFooter : MJRefreshFooter @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshBackFooter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
51
```objective-c // : path_to_url // : path_to_url // MJRefreshHeader.m // MJRefreshExample // // Created by MJ Lee on 15/3/4. // #import "MJRefreshHeader.h" @interface MJRefreshHeader() @property (assign, nonatomic) CGFloat insetTDelta; @end @implementation MJRefreshHeader #pragma mark - + (instancetype)headerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock { MJRefreshHeader *cmp = [[self alloc] init]; cmp.refreshingBlock = refreshingBlock; return cmp; } + (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action { MJRefreshHeader *cmp = [[self alloc] init]; [cmp setRefreshingTarget:target refreshingAction:action]; return cmp; } #pragma mark - - (void)prepare { [super prepare]; // key self.lastUpdatedTimeKey = MJRefreshHeaderLastUpdatedTimeKey; // self.mj_h = MJRefreshHeaderHeight; } - (void)placeSubviews { [super placeSubviews]; // y(YplaceSubviewsy) self.mj_y = - self.mj_h - self.ignoredScrollViewContentInsetTop; } - (void)scrollViewContentOffsetDidChange:(NSDictionary *)change { [super scrollViewContentOffsetDidChange:change]; // refreshing if (self.state == MJRefreshStateRefreshing) { if (self.window == nil) return; // sectionheader CGFloat insetT = - self.scrollView.mj_offsetY > _scrollViewOriginalInset.top ? - self.scrollView.mj_offsetY : _scrollViewOriginalInset.top; insetT = insetT > self.mj_h + _scrollViewOriginalInset.top ? self.mj_h + _scrollViewOriginalInset.top : insetT; self.scrollView.mj_insetT = insetT; self.insetTDelta = _scrollViewOriginalInset.top - insetT; return; } // contentInset _scrollViewOriginalInset = self.scrollView.contentInset; // contentOffset CGFloat offsetY = self.scrollView.mj_offsetY; // offsetY CGFloat happenOffsetY = - self.scrollViewOriginalInset.top; // // >= -> > if (offsetY > happenOffsetY) return; // CGFloat normal2pullingOffsetY = happenOffsetY - self.mj_h; CGFloat pullingPercent = (happenOffsetY - offsetY) / self.mj_h; if (self.scrollView.isDragging) { // self.pullingPercent = pullingPercent; if (self.state == MJRefreshStateIdle && offsetY < normal2pullingOffsetY) { // self.state = MJRefreshStatePulling; } else if (self.state == MJRefreshStatePulling && offsetY >= normal2pullingOffsetY) { // self.state = MJRefreshStateIdle; } } else if (self.state == MJRefreshStatePulling) {// && // [self beginRefreshing]; } else if (pullingPercent < 1) { self.pullingPercent = pullingPercent; } } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // if (state == MJRefreshStateIdle) { if (oldState != MJRefreshStateRefreshing) return; // [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:self.lastUpdatedTimeKey]; [[NSUserDefaults standardUserDefaults] synchronize]; // insetoffset [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{ self.scrollView.mj_insetT += self.insetTDelta; // if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0; } completion:^(BOOL finished) { self.pullingPercent = 0.0; }]; } else if (state == MJRefreshStateRefreshing) { [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ // CGFloat top = self.scrollViewOriginalInset.top + self.mj_h; self.scrollView.mj_insetT = top; // self.scrollView.mj_offsetY = - top; } completion:^(BOOL finished) { [self executeRefreshingCallback]; }]; } } - (void)drawRect:(CGRect)rect { [super drawRect:rect]; } #pragma mark - - (void)endRefreshing { if ([self.scrollView isKindOfClass:[UICollectionView class]]) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [super endRefreshing]; }); } else { [super endRefreshing]; } } - (NSDate *)lastUpdatedTime { return [[NSUserDefaults standardUserDefaults] objectForKey:self.lastUpdatedTimeKey]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshHeader.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,030
```objective-c // : path_to_url // : path_to_url // MJRefreshComponent.m // MJRefreshExample // // Created by MJ Lee on 15/3/4. // #import "MJRefreshComponent.h" #import "MJRefreshConst.h" #import "UIView+MJExtension.h" #import "UIScrollView+MJRefresh.h" @interface MJRefreshComponent() @property (strong, nonatomic) UIPanGestureRecognizer *pan; @end @implementation MJRefreshComponent #pragma mark - - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // [self prepare]; // self.state = MJRefreshStateIdle; } return self; } - (void)prepare { // self.autoresizingMask = UIViewAutoresizingFlexibleWidth; self.backgroundColor = [UIColor clearColor]; } - (void)layoutSubviews { [super layoutSubviews]; [self placeSubviews]; } - (void)placeSubviews{} - (void)willMoveToSuperview:(UIView *)newSuperview { [super willMoveToSuperview:newSuperview]; // UIScrollView if (newSuperview && ![newSuperview isKindOfClass:[UIScrollView class]]) return; // [self removeObservers]; if (newSuperview) { // // self.mj_w = newSuperview.mj_w; // self.mj_x = 0; // UIScrollView _scrollView = (UIScrollView *)newSuperview; // _scrollView.alwaysBounceVertical = YES; // UIScrollViewcontentInset _scrollViewOriginalInset = _scrollView.contentInset; // [self addObservers]; } } - (void)drawRect:(CGRect)rect { [super drawRect:rect]; if (self.state == MJRefreshStateWillRefresh) { // viewbeginRefreshing self.state = MJRefreshStateRefreshing; } } #pragma mark - KVO - (void)addObservers { NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld; [self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentOffset options:options context:nil]; [self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentSize options:options context:nil]; self.pan = self.scrollView.panGestureRecognizer; [self.pan addObserver:self forKeyPath:MJRefreshKeyPathPanState options:options context:nil]; } - (void)removeObservers { [self.superview removeObserver:self forKeyPath:MJRefreshKeyPathContentOffset]; [self.superview removeObserver:self forKeyPath:MJRefreshKeyPathContentSize];; [self.pan removeObserver:self forKeyPath:MJRefreshKeyPathPanState]; self.pan = nil; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { // if (!self.userInteractionEnabled) return; // if ([keyPath isEqualToString:MJRefreshKeyPathContentSize]) { [self scrollViewContentSizeDidChange:change]; } // if (self.hidden) return; if ([keyPath isEqualToString:MJRefreshKeyPathContentOffset]) { [self scrollViewContentOffsetDidChange:change]; } else if ([keyPath isEqualToString:MJRefreshKeyPathPanState]) { [self scrollViewPanStateDidChange:change]; } } - (void)scrollViewContentOffsetDidChange:(NSDictionary *)change{} - (void)scrollViewContentSizeDidChange:(NSDictionary *)change{} - (void)scrollViewPanStateDidChange:(NSDictionary *)change{} #pragma mark - #pragma mark - (void)setRefreshingTarget:(id)target refreshingAction:(SEL)action { self.refreshingTarget = target; self.refreshingAction = action; } #pragma mark - (void)beginRefreshing { [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ self.alpha = 1.0; }]; self.pullingPercent = 1.0; // if (self.window) { self.state = MJRefreshStateRefreshing; } else { self.state = MJRefreshStateWillRefresh; // () [self setNeedsDisplay]; } } #pragma mark - (void)endRefreshing { self.state = MJRefreshStateIdle; } #pragma mark - (BOOL)isRefreshing { return self.state == MJRefreshStateRefreshing || self.state == MJRefreshStateWillRefresh; } #pragma mark - (void)setAutoChangeAlpha:(BOOL)autoChangeAlpha { self.automaticallyChangeAlpha = autoChangeAlpha; } - (BOOL)isAutoChangeAlpha { return self.isAutomaticallyChangeAlpha; } - (void)setAutomaticallyChangeAlpha:(BOOL)automaticallyChangeAlpha { _automaticallyChangeAlpha = automaticallyChangeAlpha; if (self.isRefreshing) return; if (automaticallyChangeAlpha) { self.alpha = self.pullingPercent; } else { self.alpha = 1.0; } } #pragma mark - (void)setPullingPercent:(CGFloat)pullingPercent { _pullingPercent = pullingPercent; if (self.isRefreshing) return; if (self.isAutomaticallyChangeAlpha) { self.alpha = pullingPercent; } } #pragma mark - - (void)executeRefreshingCallback { dispatch_async(dispatch_get_main_queue(), ^{ if (self.refreshingBlock) { self.refreshingBlock(); } if ([self.refreshingTarget respondsToSelector:self.refreshingAction]) { MJRefreshMsgSend(MJRefreshMsgTarget(self.refreshingTarget), self.refreshingAction, self); } }); } @end @implementation UILabel(MJRefresh) + (instancetype)label { UILabel *label = [[self alloc] init]; label.font = MJRefreshLabelFont; label.textColor = MJRefreshLabelTextColor; label.autoresizingMask = UIViewAutoresizingFlexibleWidth; label.textAlignment = NSTextAlignmentCenter; label.backgroundColor = [UIColor clearColor]; return label; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Base/MJRefreshComponent.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,284
```objective-c // // MJRefreshStateHeader.m // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshStateHeader.h" @interface MJRefreshStateHeader() { /** label */ __unsafe_unretained UILabel *_lastUpdatedTimeLabel; /** label */ __unsafe_unretained UILabel *_stateLabel; } /** */ @property (strong, nonatomic) NSMutableDictionary *stateTitles; @end @implementation MJRefreshStateHeader #pragma mark - - (NSMutableDictionary *)stateTitles { if (!_stateTitles) { self.stateTitles = [NSMutableDictionary dictionary]; } return _stateTitles; } - (UILabel *)stateLabel { if (!_stateLabel) { [self addSubview:_stateLabel = [UILabel label]]; } return _stateLabel; } - (UILabel *)lastUpdatedTimeLabel { if (!_lastUpdatedTimeLabel) { [self addSubview:_lastUpdatedTimeLabel = [UILabel label]]; } return _lastUpdatedTimeLabel; } #pragma mark - - (void)setTitle:(NSString *)title forState:(MJRefreshState)state { if (title == nil) return; self.stateTitles[@(state)] = title; self.stateLabel.text = self.stateTitles[@(self.state)]; } #pragma mark - 9.xcurrentCalendar8.0API - (NSCalendar *)currentCalendar { if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) { return [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]; } return [NSCalendar currentCalendar]; } #pragma mark key - (void)setLastUpdatedTimeKey:(NSString *)lastUpdatedTimeKey { [super setLastUpdatedTimeKey:lastUpdatedTimeKey]; // label if (self.lastUpdatedTimeLabel.hidden) return; NSDate *lastUpdatedTime = [[NSUserDefaults standardUserDefaults] objectForKey:lastUpdatedTimeKey]; // block if (self.lastUpdatedTimeText) { self.lastUpdatedTimeLabel.text = self.lastUpdatedTimeText(lastUpdatedTime); return; } if (lastUpdatedTime) { // 1. NSCalendar *calendar = [self currentCalendar]; NSUInteger unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour |NSCalendarUnitMinute; NSDateComponents *cmp1 = [calendar components:unitFlags fromDate:lastUpdatedTime]; NSDateComponents *cmp2 = [calendar components:unitFlags fromDate:[NSDate date]]; // 2. NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; if ([cmp1 day] == [cmp2 day]) { // formatter.dateFormat = @" HH:mm"; } else if ([cmp1 year] == [cmp2 year]) { // formatter.dateFormat = @"MM-dd HH:mm"; } else { formatter.dateFormat = @"yyyy-MM-dd HH:mm"; } NSString *time = [formatter stringFromDate:lastUpdatedTime]; // 3. self.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@", time]; } else { self.lastUpdatedTimeLabel.text = @""; } } #pragma mark - - (void)prepare { [super prepare]; // [self setTitle:MJRefreshHeaderIdleText forState:MJRefreshStateIdle]; [self setTitle:MJRefreshHeaderPullingText forState:MJRefreshStatePulling]; [self setTitle:MJRefreshHeaderRefreshingText forState:MJRefreshStateRefreshing]; } - (void)placeSubviews { [super placeSubviews]; if (self.stateLabel.hidden) return; BOOL noConstrainsOnStatusLabel = self.stateLabel.constraints.count == 0; if (self.lastUpdatedTimeLabel.hidden) { // if (noConstrainsOnStatusLabel) self.stateLabel.frame = self.bounds; } else { CGFloat stateLabelH = self.mj_h * 0.5; // if (noConstrainsOnStatusLabel) { self.stateLabel.mj_x = 0; self.stateLabel.mj_y = 0; self.stateLabel.mj_w = self.mj_w; self.stateLabel.mj_h = stateLabelH; } // if (self.lastUpdatedTimeLabel.constraints.count == 0) { self.lastUpdatedTimeLabel.mj_x = 0; self.lastUpdatedTimeLabel.mj_y = stateLabelH; self.lastUpdatedTimeLabel.mj_w = self.mj_w; self.lastUpdatedTimeLabel.mj_h = self.mj_h - self.lastUpdatedTimeLabel.mj_y; } } } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // self.stateLabel.text = self.stateTitles[@(state)]; // key self.lastUpdatedTimeKey = self.lastUpdatedTimeKey; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Header/MJRefreshStateHeader.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,033
```objective-c // // MJRefreshGifHeader.m // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshGifHeader.h" @interface MJRefreshGifHeader() { __unsafe_unretained UIImageView *_gifView; } /** */ @property (strong, nonatomic) NSMutableDictionary *stateImages; /** */ @property (strong, nonatomic) NSMutableDictionary *stateDurations; @end @implementation MJRefreshGifHeader #pragma mark - - (UIImageView *)gifView { if (!_gifView) { UIImageView *gifView = [[UIImageView alloc] init]; [self addSubview:_gifView = gifView]; } return _gifView; } - (NSMutableDictionary *)stateImages { if (!_stateImages) { self.stateImages = [NSMutableDictionary dictionary]; } return _stateImages; } - (NSMutableDictionary *)stateDurations { if (!_stateDurations) { self.stateDurations = [NSMutableDictionary dictionary]; } return _stateDurations; } #pragma mark - - (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state { if (images == nil) return; self.stateImages[@(state)] = images; self.stateDurations[@(state)] = @(duration); /* */ UIImage *image = [images firstObject]; if (image.size.height > self.mj_h) { self.mj_h = image.size.height; } } - (void)setImages:(NSArray *)images forState:(MJRefreshState)state { [self setImages:images duration:images.count * 0.1 forState:state]; } #pragma mark - - (void)setPullingPercent:(CGFloat)pullingPercent { [super setPullingPercent:pullingPercent]; NSArray *images = self.stateImages[@(MJRefreshStateIdle)]; if (self.state != MJRefreshStateIdle || images.count == 0) return; // [self.gifView stopAnimating]; // NSUInteger index = images.count * pullingPercent; if (index >= images.count) index = images.count - 1; self.gifView.image = images[index]; } - (void)placeSubviews { [super placeSubviews]; if (self.gifView.constraints.count) return; self.gifView.frame = self.bounds; if (self.stateLabel.hidden && self.lastUpdatedTimeLabel.hidden) { self.gifView.contentMode = UIViewContentModeCenter; } else { self.gifView.contentMode = UIViewContentModeRight; self.gifView.mj_w = self.mj_w * 0.5 - 90; } } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // if (state == MJRefreshStatePulling || state == MJRefreshStateRefreshing) { NSArray *images = self.stateImages[@(state)]; if (images.count == 0) return; [self.gifView stopAnimating]; if (images.count == 1) { // self.gifView.image = [images lastObject]; } else { // self.gifView.animationImages = images; self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue]; [self.gifView startAnimating]; } } else if (state == MJRefreshStateIdle) { [self.gifView stopAnimating]; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Header/MJRefreshGifHeader.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
767
```objective-c // // MJRefreshNormalHeader.m // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshNormalHeader.h" @interface MJRefreshNormalHeader() { __unsafe_unretained UIImageView *_arrowView; } @property (weak, nonatomic) UIActivityIndicatorView *loadingView; @end @implementation MJRefreshNormalHeader #pragma mark - - (UIImageView *)arrowView { if (!_arrowView) { UIImage *image = [UIImage imageNamed:MJRefreshSrcName(@"arrow.png")] ?: [UIImage imageNamed:MJRefreshFrameworkSrcName(@"arrow.png")]; UIImageView *arrowView = [[UIImageView alloc] initWithImage:image]; [self addSubview:_arrowView = arrowView]; } return _arrowView; } - (UIActivityIndicatorView *)loadingView { if (!_loadingView) { UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:self.activityIndicatorViewStyle]; loadingView.hidesWhenStopped = YES; [self addSubview:_loadingView = loadingView]; } return _loadingView; } #pragma mark - - (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle { _activityIndicatorViewStyle = activityIndicatorViewStyle; self.loadingView = nil; [self setNeedsLayout]; } #pragma makr - - (void)prepare { [super prepare]; self.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; } - (void)placeSubviews { [super placeSubviews]; // CGFloat arrowCenterX = self.mj_w * 0.5; if (!self.stateLabel.hidden) { arrowCenterX -= 100; } CGFloat arrowCenterY = self.mj_h * 0.5; CGPoint arrowCenter = CGPointMake(arrowCenterX, arrowCenterY); // if (self.arrowView.constraints.count == 0) { self.arrowView.mj_size = self.arrowView.image.size; self.arrowView.center = arrowCenter; } // if (self.loadingView.constraints.count == 0) { self.loadingView.center = arrowCenter; } } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // if (state == MJRefreshStateIdle) { if (oldState == MJRefreshStateRefreshing) { self.arrowView.transform = CGAffineTransformIdentity; [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{ self.loadingView.alpha = 0.0; } completion:^(BOOL finished) { // idle if (self.state != MJRefreshStateIdle) return; self.loadingView.alpha = 1.0; [self.loadingView stopAnimating]; self.arrowView.hidden = NO; }]; } else { [self.loadingView stopAnimating]; self.arrowView.hidden = NO; [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ self.arrowView.transform = CGAffineTransformIdentity; }]; } } else if (state == MJRefreshStatePulling) { [self.loadingView stopAnimating]; self.arrowView.hidden = NO; [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI); }]; } else if (state == MJRefreshStateRefreshing) { self.loadingView.alpha = 1.0; // refreshing -> idle [self.loadingView startAnimating]; self.arrowView.hidden = YES; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Header/MJRefreshNormalHeader.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
752
```objective-c // // MJRefreshGifHeader.h // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshStateHeader.h" @interface MJRefreshGifHeader : MJRefreshStateHeader @property (weak, nonatomic, readonly) UIImageView *gifView; /** stateimages duration*/ - (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state; - (void)setImages:(NSArray *)images forState:(MJRefreshState)state; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Header/MJRefreshGifHeader.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
113
```objective-c // // MJRefreshNormalHeader.h // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshStateHeader.h" @interface MJRefreshNormalHeader : MJRefreshStateHeader @property (weak, nonatomic, readonly) UIImageView *arrowView; /** */ @property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Header/MJRefreshNormalHeader.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
83
```objective-c // // MJRefreshStateHeader.h // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshHeader.h" @interface MJRefreshStateHeader : MJRefreshHeader #pragma mark - /** block */ @property (copy, nonatomic) NSString *(^lastUpdatedTimeText)(NSDate *lastUpdatedTime); /** label */ @property (weak, nonatomic, readonly) UILabel *lastUpdatedTimeLabel; #pragma mark - /** label */ @property (weak, nonatomic, readonly) UILabel *stateLabel; /** state */ - (void)setTitle:(NSString *)title forState:(MJRefreshState)state; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Header/MJRefreshStateHeader.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
136
```objective-c // // MJRefreshAutoStateFooter.h // MJRefreshExample // // Created by MJ Lee on 15/6/13. // #import "MJRefreshAutoFooter.h" @interface MJRefreshAutoStateFooter : MJRefreshAutoFooter /** label */ @property (weak, nonatomic, readonly) UILabel *stateLabel; /** state */ - (void)setTitle:(NSString *)title forState:(MJRefreshState)state; /** */ @property (assign, nonatomic, getter=isRefreshingTitleHidden) BOOL refreshingTitleHidden; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
111
```objective-c // // MJRefreshAutoGifFooter.m // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshAutoGifFooter.h" @interface MJRefreshAutoGifFooter() { __unsafe_unretained UIImageView *_gifView; } /** */ @property (strong, nonatomic) NSMutableDictionary *stateImages; /** */ @property (strong, nonatomic) NSMutableDictionary *stateDurations; @end @implementation MJRefreshAutoGifFooter #pragma mark - - (UIImageView *)gifView { if (!_gifView) { UIImageView *gifView = [[UIImageView alloc] init]; [self addSubview:_gifView = gifView]; } return _gifView; } - (NSMutableDictionary *)stateImages { if (!_stateImages) { self.stateImages = [NSMutableDictionary dictionary]; } return _stateImages; } - (NSMutableDictionary *)stateDurations { if (!_stateDurations) { self.stateDurations = [NSMutableDictionary dictionary]; } return _stateDurations; } #pragma mark - - (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state { if (images == nil) return; self.stateImages[@(state)] = images; self.stateDurations[@(state)] = @(duration); /* */ UIImage *image = [images firstObject]; if (image.size.height > self.mj_h) { self.mj_h = image.size.height; } } - (void)setImages:(NSArray *)images forState:(MJRefreshState)state { [self setImages:images duration:images.count * 0.1 forState:state]; } #pragma mark - - (void)placeSubviews { [super placeSubviews]; if (self.gifView.constraints.count) return; self.gifView.frame = self.bounds; if (self.isRefreshingTitleHidden) { self.gifView.contentMode = UIViewContentModeCenter; } else { self.gifView.contentMode = UIViewContentModeRight; self.gifView.mj_w = self.mj_w * 0.5 - 90; } } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // if (state == MJRefreshStateRefreshing) { NSArray *images = self.stateImages[@(state)]; if (images.count == 0) return; [self.gifView stopAnimating]; self.gifView.hidden = NO; if (images.count == 1) { // self.gifView.image = [images lastObject]; } else { // self.gifView.animationImages = images; self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue]; [self.gifView startAnimating]; } } else if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { [self.gifView stopAnimating]; self.gifView.hidden = YES; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
646
```objective-c // // MJRefreshAutoGifFooter.h // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshAutoStateFooter.h" @interface MJRefreshAutoGifFooter : MJRefreshAutoStateFooter @property (weak, nonatomic, readonly) UIImageView *gifView; /** stateimages duration*/ - (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state; - (void)setImages:(NSArray *)images forState:(MJRefreshState)state; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
117
```objective-c // // MJRefreshAutoNormalFooter.h // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshAutoStateFooter.h" @interface MJRefreshAutoNormalFooter : MJRefreshAutoStateFooter /** */ @property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
74
```objective-c // // MJRefreshAutoStateFooter.m // MJRefreshExample // // Created by MJ Lee on 15/6/13. // #import "MJRefreshAutoStateFooter.h" @interface MJRefreshAutoStateFooter() { /** label */ __unsafe_unretained UILabel *_stateLabel; } /** */ @property (strong, nonatomic) NSMutableDictionary *stateTitles; @end @implementation MJRefreshAutoStateFooter #pragma mark - - (NSMutableDictionary *)stateTitles { if (!_stateTitles) { self.stateTitles = [NSMutableDictionary dictionary]; } return _stateTitles; } - (UILabel *)stateLabel { if (!_stateLabel) { [self addSubview:_stateLabel = [UILabel label]]; } return _stateLabel; } #pragma mark - - (void)setTitle:(NSString *)title forState:(MJRefreshState)state { if (title == nil) return; self.stateTitles[@(state)] = title; self.stateLabel.text = self.stateTitles[@(self.state)]; } #pragma mark - - (void)stateLabelClick { if (self.state == MJRefreshStateIdle) { [self beginRefreshing]; } } #pragma mark - - (void)prepare { [super prepare]; // [self setTitle:MJRefreshAutoFooterIdleText forState:MJRefreshStateIdle]; [self setTitle:MJRefreshAutoFooterRefreshingText forState:MJRefreshStateRefreshing]; [self setTitle:MJRefreshAutoFooterNoMoreDataText forState:MJRefreshStateNoMoreData]; // label self.stateLabel.userInteractionEnabled = YES; [self.stateLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(stateLabelClick)]]; } - (void)placeSubviews { [super placeSubviews]; if (self.stateLabel.constraints.count) return; // self.stateLabel.frame = self.bounds; } - (void)setState:(MJRefreshState)state { MJRefreshCheckState if (self.isRefreshingTitleHidden && state == MJRefreshStateRefreshing) { self.stateLabel.text = nil; } else { self.stateLabel.text = self.stateTitles[@(state)]; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
472
```objective-c // // MJRefreshAutoNormalFooter.m // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshAutoNormalFooter.h" @interface MJRefreshAutoNormalFooter() @property (weak, nonatomic) UIActivityIndicatorView *loadingView; @end @implementation MJRefreshAutoNormalFooter #pragma mark - - (UIActivityIndicatorView *)loadingView { if (!_loadingView) { UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:self.activityIndicatorViewStyle]; loadingView.hidesWhenStopped = YES; [self addSubview:_loadingView = loadingView]; } return _loadingView; } - (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle { _activityIndicatorViewStyle = activityIndicatorViewStyle; self.loadingView = nil; [self setNeedsLayout]; } #pragma makr - - (void)prepare { [super prepare]; self.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; } - (void)placeSubviews { [super placeSubviews]; if (self.loadingView.constraints.count) return; // CGFloat loadingCenterX = self.mj_w * 0.5; if (!self.isRefreshingTitleHidden) { loadingCenterX -= 100; } CGFloat loadingCenterY = self.mj_h * 0.5; self.loadingView.center = CGPointMake(loadingCenterX, loadingCenterY); } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { [self.loadingView stopAnimating]; } else if (state == MJRefreshStateRefreshing) { [self.loadingView startAnimating]; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
389
```objective-c // // MJRefreshBackNormalFooter.h // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshBackStateFooter.h" @interface MJRefreshBackNormalFooter : MJRefreshBackStateFooter @property (weak, nonatomic, readonly) UIImageView *arrowView; /** */ @property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
87
```objective-c // // MJRefreshBackGifFooter.h // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshBackStateFooter.h" @interface MJRefreshBackGifFooter : MJRefreshBackStateFooter @property (weak, nonatomic, readonly) UIImageView *gifView; /** stateimages duration*/ - (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state; - (void)setImages:(NSArray *)images forState:(MJRefreshState)state; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
117
```objective-c // // MJRefreshBackStateFooter.h // MJRefreshExample // // Created by MJ Lee on 15/6/13. // #import "MJRefreshBackFooter.h" @interface MJRefreshBackStateFooter : MJRefreshBackFooter /** label */ @property (weak, nonatomic, readonly) UILabel *stateLabel; /** state */ - (void)setTitle:(NSString *)title forState:(MJRefreshState)state; /** statetitle */ - (NSString *)titleForState:(MJRefreshState)state; @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
110
```objective-c // // MJRefreshBackGifFooter.m // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshBackGifFooter.h" @interface MJRefreshBackGifFooter() { __unsafe_unretained UIImageView *_gifView; } /** */ @property (strong, nonatomic) NSMutableDictionary *stateImages; /** */ @property (strong, nonatomic) NSMutableDictionary *stateDurations; @end @implementation MJRefreshBackGifFooter #pragma mark - - (UIImageView *)gifView { if (!_gifView) { UIImageView *gifView = [[UIImageView alloc] init]; [self addSubview:_gifView = gifView]; } return _gifView; } - (NSMutableDictionary *)stateImages { if (!_stateImages) { self.stateImages = [NSMutableDictionary dictionary]; } return _stateImages; } - (NSMutableDictionary *)stateDurations { if (!_stateDurations) { self.stateDurations = [NSMutableDictionary dictionary]; } return _stateDurations; } #pragma mark - - (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state { if (images == nil) return; self.stateImages[@(state)] = images; self.stateDurations[@(state)] = @(duration); /* */ UIImage *image = [images firstObject]; if (image.size.height > self.mj_h) { self.mj_h = image.size.height; } } - (void)setImages:(NSArray *)images forState:(MJRefreshState)state { [self setImages:images duration:images.count * 0.1 forState:state]; } #pragma mark - - (void)setPullingPercent:(CGFloat)pullingPercent { [super setPullingPercent:pullingPercent]; NSArray *images = self.stateImages[@(MJRefreshStateIdle)]; if (self.state != MJRefreshStateIdle || images.count == 0) return; [self.gifView stopAnimating]; NSUInteger index = images.count * pullingPercent; if (index >= images.count) index = images.count - 1; self.gifView.image = images[index]; } - (void)placeSubviews { [super placeSubviews]; if (self.gifView.constraints.count) return; self.gifView.frame = self.bounds; if (self.stateLabel.hidden) { self.gifView.contentMode = UIViewContentModeCenter; } else { self.gifView.contentMode = UIViewContentModeRight; self.gifView.mj_w = self.mj_w * 0.5 - 90; } } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // if (state == MJRefreshStatePulling || state == MJRefreshStateRefreshing) { NSArray *images = self.stateImages[@(state)]; if (images.count == 0) return; self.gifView.hidden = NO; [self.gifView stopAnimating]; if (images.count == 1) { // self.gifView.image = [images lastObject]; } else { // self.gifView.animationImages = images; self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue]; [self.gifView startAnimating]; } } else if (state == MJRefreshStateIdle) { self.gifView.hidden = NO; } else if (state == MJRefreshStateNoMoreData) { self.gifView.hidden = YES; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
765
```objective-c // // MJRefreshBackNormalFooter.m // MJRefreshExample // // Created by MJ Lee on 15/4/24. // #import "MJRefreshBackNormalFooter.h" @interface MJRefreshBackNormalFooter() { __unsafe_unretained UIImageView *_arrowView; } @property (weak, nonatomic) UIActivityIndicatorView *loadingView; @end @implementation MJRefreshBackNormalFooter #pragma mark - - (UIImageView *)arrowView { if (!_arrowView) { UIImage *image = [UIImage imageNamed:MJRefreshSrcName(@"arrow.png")] ?: [UIImage imageNamed:MJRefreshFrameworkSrcName(@"arrow.png")]; UIImageView *arrowView = [[UIImageView alloc] initWithImage:image]; [self addSubview:_arrowView = arrowView]; } return _arrowView; } - (UIActivityIndicatorView *)loadingView { if (!_loadingView) { UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:self.activityIndicatorViewStyle]; loadingView.hidesWhenStopped = YES; [self addSubview:_loadingView = loadingView]; } return _loadingView; } - (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle { _activityIndicatorViewStyle = activityIndicatorViewStyle; self.loadingView = nil; [self setNeedsLayout]; } #pragma makr - - (void)prepare { [super prepare]; self.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; } - (void)placeSubviews { [super placeSubviews]; // CGFloat arrowCenterX = self.mj_w * 0.5; if (!self.stateLabel.hidden) { arrowCenterX -= 100; } CGFloat arrowCenterY = self.mj_h * 0.5; CGPoint arrowCenter = CGPointMake(arrowCenterX, arrowCenterY); // if (self.arrowView.constraints.count == 0) { self.arrowView.mj_size = self.arrowView.image.size; self.arrowView.center = arrowCenter; } // if (self.loadingView.constraints.count == 0) { self.loadingView.center = arrowCenter; } } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // if (state == MJRefreshStateIdle) { if (oldState == MJRefreshStateRefreshing) { self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI); [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{ self.loadingView.alpha = 0.0; } completion:^(BOOL finished) { self.loadingView.alpha = 1.0; [self.loadingView stopAnimating]; self.arrowView.hidden = NO; }]; } else { self.arrowView.hidden = NO; [self.loadingView stopAnimating]; [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI); }]; } } else if (state == MJRefreshStatePulling) { self.arrowView.hidden = NO; [self.loadingView stopAnimating]; [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ self.arrowView.transform = CGAffineTransformIdentity; }]; } else if (state == MJRefreshStateRefreshing) { self.arrowView.hidden = YES; [self.loadingView startAnimating]; } else if (state == MJRefreshStateNoMoreData) { self.arrowView.hidden = YES; [self.loadingView stopAnimating]; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
758
```objective-c // // MJRefreshBackStateFooter.m // MJRefreshExample // // Created by MJ Lee on 15/6/13. // #import "MJRefreshBackStateFooter.h" @interface MJRefreshBackStateFooter() { /** label */ __unsafe_unretained UILabel *_stateLabel; } /** */ @property (strong, nonatomic) NSMutableDictionary *stateTitles; @end @implementation MJRefreshBackStateFooter #pragma mark - - (NSMutableDictionary *)stateTitles { if (!_stateTitles) { self.stateTitles = [NSMutableDictionary dictionary]; } return _stateTitles; } - (UILabel *)stateLabel { if (!_stateLabel) { [self addSubview:_stateLabel = [UILabel label]]; } return _stateLabel; } #pragma mark - - (void)setTitle:(NSString *)title forState:(MJRefreshState)state { if (title == nil) return; self.stateTitles[@(state)] = title; self.stateLabel.text = self.stateTitles[@(self.state)]; } - (NSString *)titleForState:(MJRefreshState)state { return self.stateTitles[@(state)]; } #pragma mark - - (void)prepare { [super prepare]; // [self setTitle:MJRefreshBackFooterIdleText forState:MJRefreshStateIdle]; [self setTitle:MJRefreshBackFooterPullingText forState:MJRefreshStatePulling]; [self setTitle:MJRefreshBackFooterRefreshingText forState:MJRefreshStateRefreshing]; [self setTitle:MJRefreshBackFooterNoMoreDataText forState:MJRefreshStateNoMoreData]; } - (void)placeSubviews { [super placeSubviews]; if (self.stateLabel.constraints.count) return; // self.stateLabel.frame = self.bounds; } - (void)setState:(MJRefreshState)state { MJRefreshCheckState // self.stateLabel.text = self.stateTitles[@(state)]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
419
```objective-c // // NSLayoutConstraint+MASDebugAdditions.m // Masonry // // Created by Jonas Budelmann on 3/08/13. // #import "NSLayoutConstraint+MASDebugAdditions.h" #import "MASConstraint.h" #import "MASLayoutConstraint.h" @implementation NSLayoutConstraint (MASDebugAdditions) #pragma mark - description maps + (NSDictionary *)layoutRelationDescriptionsByValue { static dispatch_once_t once; static NSDictionary *descriptionMap; dispatch_once(&once, ^{ descriptionMap = @{ @(NSLayoutRelationEqual) : @"==", @(NSLayoutRelationGreaterThanOrEqual) : @">=", @(NSLayoutRelationLessThanOrEqual) : @"<=", }; }); return descriptionMap; } + (NSDictionary *)layoutAttributeDescriptionsByValue { static dispatch_once_t once; static NSDictionary *descriptionMap; dispatch_once(&once, ^{ descriptionMap = @{ @(NSLayoutAttributeTop) : @"top", @(NSLayoutAttributeLeft) : @"left", @(NSLayoutAttributeBottom) : @"bottom", @(NSLayoutAttributeRight) : @"right", @(NSLayoutAttributeLeading) : @"leading", @(NSLayoutAttributeTrailing) : @"trailing", @(NSLayoutAttributeWidth) : @"width", @(NSLayoutAttributeHeight) : @"height", @(NSLayoutAttributeCenterX) : @"centerX", @(NSLayoutAttributeCenterY) : @"centerY", @(NSLayoutAttributeBaseline) : @"baseline", #if TARGET_OS_IPHONE @(NSLayoutAttributeLeftMargin) : @"leftMargin", @(NSLayoutAttributeRightMargin) : @"rightMargin", @(NSLayoutAttributeTopMargin) : @"topMargin", @(NSLayoutAttributeBottomMargin) : @"bottomMargin", @(NSLayoutAttributeLeadingMargin) : @"leadingMargin", @(NSLayoutAttributeTrailingMargin) : @"trailingMargin", @(NSLayoutAttributeCenterXWithinMargins) : @"centerXWithinMargins", @(NSLayoutAttributeCenterYWithinMargins) : @"centerYWithinMargins", #endif }; }); return descriptionMap; } + (NSDictionary *)layoutPriorityDescriptionsByValue { static dispatch_once_t once; static NSDictionary *descriptionMap; dispatch_once(&once, ^{ #if TARGET_OS_IPHONE descriptionMap = @{ @(MASLayoutPriorityDefaultHigh) : @"high", @(MASLayoutPriorityDefaultLow) : @"low", @(MASLayoutPriorityDefaultMedium) : @"medium", @(MASLayoutPriorityRequired) : @"required", @(MASLayoutPriorityFittingSizeLevel) : @"fitting size", }; #elif TARGET_OS_MAC descriptionMap = @{ @(MASLayoutPriorityDefaultHigh) : @"high", @(MASLayoutPriorityDragThatCanResizeWindow) : @"drag can resize window", @(MASLayoutPriorityDefaultMedium) : @"medium", @(MASLayoutPriorityWindowSizeStayPut) : @"window size stay put", @(MASLayoutPriorityDragThatCannotResizeWindow) : @"drag cannot resize window", @(MASLayoutPriorityDefaultLow) : @"low", @(MASLayoutPriorityFittingSizeCompression) : @"fitting size", @(MASLayoutPriorityRequired) : @"required", }; #endif }); return descriptionMap; } #pragma mark - description override + (NSString *)descriptionForObject:(id)obj { if ([obj respondsToSelector:@selector(mas_key)] && [obj mas_key]) { return [NSString stringWithFormat:@"%@:%@", [obj class], [obj mas_key]]; } return [NSString stringWithFormat:@"%@:%p", [obj class], obj]; } - (NSString *)description { NSMutableString *description = [[NSMutableString alloc] initWithString:@"<"]; [description appendString:[self.class descriptionForObject:self]]; [description appendFormat:@" %@", [self.class descriptionForObject:self.firstItem]]; if (self.firstAttribute != NSLayoutAttributeNotAnAttribute) { [description appendFormat:@".%@", [self.class.layoutAttributeDescriptionsByValue objectForKey:@(self.firstAttribute)]]; } [description appendFormat:@" %@", [self.class.layoutRelationDescriptionsByValue objectForKey:@(self.relation)]]; if (self.secondItem) { [description appendFormat:@" %@", [self.class descriptionForObject:self.secondItem]]; } if (self.secondAttribute != NSLayoutAttributeNotAnAttribute) { [description appendFormat:@".%@", [self.class.layoutAttributeDescriptionsByValue objectForKey:@(self.secondAttribute)]]; } if (self.multiplier != 1) { [description appendFormat:@" * %g", self.multiplier]; } if (self.secondAttribute == NSLayoutAttributeNotAnAttribute) { [description appendFormat:@" %g", self.constant]; } else { if (self.constant) { [description appendFormat:@" %@ %g", (self.constant < 0 ? @"-" : @"+"), ABS(self.constant)]; } } if (self.priority != MASLayoutPriorityRequired) { [description appendFormat:@" ^%@", [self.class.layoutPriorityDescriptionsByValue objectForKey:@(self.priority)] ?: [NSNumber numberWithDouble:self.priority]]; } [description appendString:@">"]; return description; } @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/NSLayoutConstraint+MASDebugAdditions.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,133
```objective-c // // MASLayoutConstraint.h // Masonry // // Created by Jonas Budelmann on 3/08/13. // #import "MASUtilities.h" /** * When you are debugging or printing the constraints attached to a view this subclass * makes it easier to identify which constraints have been created via Masonry */ @interface MASLayoutConstraint : NSLayoutConstraint /** * a key to associate with this constraint */ @property (nonatomic, strong) id mas_key; @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASLayoutConstraint.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
101
```objective-c // // MASConstraintBuilder.m // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASConstraintMaker.h" #import "MASViewConstraint.h" #import "MASCompositeConstraint.h" #import "MASConstraint+Private.h" #import "MASViewAttribute.h" #import "View+MASAdditions.h" @interface MASConstraintMaker () <MASConstraintDelegate> @property (nonatomic, weak) MAS_VIEW *view; @property (nonatomic, strong) NSMutableArray *constraints; @end @implementation MASConstraintMaker - (id)initWithView:(MAS_VIEW *)view { self = [super init]; if (!self) return nil; self.view = view; self.constraints = NSMutableArray.new; return self; } - (NSArray *)install { if (self.removeExisting) { NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view]; for (MASConstraint *constraint in installedConstraints) { [constraint uninstall]; } } NSArray *constraints = self.constraints.copy; for (MASConstraint *constraint in constraints) { constraint.updateExisting = self.updateExisting; [constraint install]; } [self.constraints removeAllObjects]; return constraints; } #pragma mark - MASConstraintDelegate - (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { NSUInteger index = [self.constraints indexOfObject:constraint]; NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint); [self.constraints replaceObjectAtIndex:index withObject:replacementConstraint]; } - (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { MASViewAttribute *viewAttribute = [[MASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute]; MASViewConstraint *newConstraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute]; if ([constraint isKindOfClass:MASViewConstraint.class]) { //replace with composite constraint NSArray *children = @[constraint, newConstraint]; MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; compositeConstraint.delegate = self; [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint]; return compositeConstraint; } if (!constraint) { newConstraint.delegate = self; [self.constraints addObject:newConstraint]; } return newConstraint; } - (MASConstraint *)addConstraintWithAttributes:(MASAttribute)attrs { __unused MASAttribute anyAttribute = (MASAttributeLeft | MASAttributeRight | MASAttributeTop | MASAttributeBottom | MASAttributeLeading | MASAttributeTrailing | MASAttributeWidth | MASAttributeHeight | MASAttributeCenterX | MASAttributeCenterY | MASAttributeBaseline #if TARGET_OS_IPHONE | MASAttributeLeftMargin | MASAttributeRightMargin | MASAttributeTopMargin | MASAttributeBottomMargin | MASAttributeLeadingMargin | MASAttributeTrailingMargin | MASAttributeCenterXWithinMargins | MASAttributeCenterYWithinMargins #endif ); NSAssert((attrs & anyAttribute) != 0, @"You didn't pass any attribute to make.attributes(...)"); NSMutableArray *attributes = [NSMutableArray array]; if (attrs & MASAttributeLeft) [attributes addObject:self.view.mas_left]; if (attrs & MASAttributeRight) [attributes addObject:self.view.mas_right]; if (attrs & MASAttributeTop) [attributes addObject:self.view.mas_top]; if (attrs & MASAttributeBottom) [attributes addObject:self.view.mas_bottom]; if (attrs & MASAttributeLeading) [attributes addObject:self.view.mas_leading]; if (attrs & MASAttributeTrailing) [attributes addObject:self.view.mas_trailing]; if (attrs & MASAttributeWidth) [attributes addObject:self.view.mas_width]; if (attrs & MASAttributeHeight) [attributes addObject:self.view.mas_height]; if (attrs & MASAttributeCenterX) [attributes addObject:self.view.mas_centerX]; if (attrs & MASAttributeCenterY) [attributes addObject:self.view.mas_centerY]; if (attrs & MASAttributeBaseline) [attributes addObject:self.view.mas_baseline]; #if TARGET_OS_IPHONE if (attrs & MASAttributeLeftMargin) [attributes addObject:self.view.mas_leftMargin]; if (attrs & MASAttributeRightMargin) [attributes addObject:self.view.mas_rightMargin]; if (attrs & MASAttributeTopMargin) [attributes addObject:self.view.mas_topMargin]; if (attrs & MASAttributeBottomMargin) [attributes addObject:self.view.mas_bottomMargin]; if (attrs & MASAttributeLeadingMargin) [attributes addObject:self.view.mas_leadingMargin]; if (attrs & MASAttributeTrailingMargin) [attributes addObject:self.view.mas_trailingMargin]; if (attrs & MASAttributeCenterXWithinMargins) [attributes addObject:self.view.mas_centerXWithinMargins]; if (attrs & MASAttributeCenterYWithinMargins) [attributes addObject:self.view.mas_centerYWithinMargins]; #endif NSMutableArray *children = [NSMutableArray arrayWithCapacity:attributes.count]; for (MASViewAttribute *a in attributes) { [children addObject:[[MASViewConstraint alloc] initWithFirstViewAttribute:a]]; } MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; constraint.delegate = self; [self.constraints addObject:constraint]; return constraint; } #pragma mark - standard Attributes - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute]; } - (MASConstraint *)left { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; } - (MASConstraint *)top { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; } - (MASConstraint *)right { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; } - (MASConstraint *)bottom { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; } - (MASConstraint *)leading { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; } - (MASConstraint *)trailing { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; } - (MASConstraint *)width { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; } - (MASConstraint *)height { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; } - (MASConstraint *)centerX { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; } - (MASConstraint *)centerY { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; } - (MASConstraint *)baseline { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; } - (MASConstraint *(^)(MASAttribute))attributes { return ^(MASAttribute attrs){ return [self addConstraintWithAttributes:attrs]; }; } #if TARGET_OS_IPHONE - (MASConstraint *)leftMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; } - (MASConstraint *)rightMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; } - (MASConstraint *)topMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; } - (MASConstraint *)bottomMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; } - (MASConstraint *)leadingMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; } - (MASConstraint *)trailingMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; } - (MASConstraint *)centerXWithinMargins { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; } - (MASConstraint *)centerYWithinMargins { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; } #endif #pragma mark - composite Attributes - (MASConstraint *)edges { return [self addConstraintWithAttributes:MASAttributeTop | MASAttributeLeft | MASAttributeRight | MASAttributeBottom]; } - (MASConstraint *)size { return [self addConstraintWithAttributes:MASAttributeWidth | MASAttributeHeight]; } - (MASConstraint *)center { return [self addConstraintWithAttributes:MASAttributeCenterX | MASAttributeCenterY]; } #pragma mark - grouping - (MASConstraint *(^)(dispatch_block_t group))group { return ^id(dispatch_block_t group) { NSInteger previousCount = self.constraints.count; group(); NSArray *children = [self.constraints subarrayWithRange:NSMakeRange(previousCount, self.constraints.count - previousCount)]; MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; constraint.delegate = self; return constraint; }; } @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASConstraintMaker.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,826
```objective-c // // MASCompositeConstraint.h // Masonry // // Created by Jonas Budelmann on 21/07/13. // #import "MASConstraint.h" #import "MASUtilities.h" /** * A group of MASConstraint objects */ @interface MASCompositeConstraint : MASConstraint /** * Creates a composite with a predefined array of children * * @param children child MASConstraints * * @return a composite constraint */ - (id)initWithChildren:(NSArray *)children; @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASCompositeConstraint.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
106
```objective-c // // MASConstraint.h // Masonry // // Created by Jonas Budelmann on 22/07/13. // #import "MASUtilities.h" /** * Enables Constraints to be created with chainable syntax * Constraint can represent single NSLayoutConstraint (MASViewConstraint) * or a group of NSLayoutConstraints (MASComposisteConstraint) */ @interface MASConstraint : NSObject // Chaining Support /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight */ - (MASConstraint * (^)(MASEdgeInsets insets))insets; /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeWidth, NSLayoutAttributeHeight */ - (MASConstraint * (^)(CGSize offset))sizeOffset; /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY */ - (MASConstraint * (^)(CGPoint offset))centerOffset; /** * Modifies the NSLayoutConstraint constant */ - (MASConstraint * (^)(CGFloat offset))offset; /** * Modifies the NSLayoutConstraint constant based on a value type */ - (MASConstraint * (^)(NSValue *value))valueOffset; /** * Sets the NSLayoutConstraint multiplier property */ - (MASConstraint * (^)(CGFloat multiplier))multipliedBy; /** * Sets the NSLayoutConstraint multiplier to 1.0/dividedBy */ - (MASConstraint * (^)(CGFloat divider))dividedBy; /** * Sets the NSLayoutConstraint priority to a float or MASLayoutPriority */ - (MASConstraint * (^)(MASLayoutPriority priority))priority; /** * Sets the NSLayoutConstraint priority to MASLayoutPriorityLow */ - (MASConstraint * (^)())priorityLow; /** * Sets the NSLayoutConstraint priority to MASLayoutPriorityMedium */ - (MASConstraint * (^)())priorityMedium; /** * Sets the NSLayoutConstraint priority to MASLayoutPriorityHigh */ - (MASConstraint * (^)())priorityHigh; /** * Sets the constraint relation to NSLayoutRelationEqual * returns a block which accepts one of the following: * MASViewAttribute, UIView, NSValue, NSArray * see readme for more details. */ - (MASConstraint * (^)(id attr))equalTo; /** * Sets the constraint relation to NSLayoutRelationGreaterThanOrEqual * returns a block which accepts one of the following: * MASViewAttribute, UIView, NSValue, NSArray * see readme for more details. */ - (MASConstraint * (^)(id attr))greaterThanOrEqualTo; /** * Sets the constraint relation to NSLayoutRelationLessThanOrEqual * returns a block which accepts one of the following: * MASViewAttribute, UIView, NSValue, NSArray * see readme for more details. */ - (MASConstraint * (^)(id attr))lessThanOrEqualTo; /** * Optional semantic property which has no effect but improves the readability of constraint */ - (MASConstraint *)with; /** * Optional semantic property which has no effect but improves the readability of constraint */ - (MASConstraint *)and; /** * Creates a new MASCompositeConstraint with the called attribute and reciever */ - (MASConstraint *)left; - (MASConstraint *)top; - (MASConstraint *)right; - (MASConstraint *)bottom; - (MASConstraint *)leading; - (MASConstraint *)trailing; - (MASConstraint *)width; - (MASConstraint *)height; - (MASConstraint *)centerX; - (MASConstraint *)centerY; - (MASConstraint *)baseline; #if TARGET_OS_IPHONE - (MASConstraint *)leftMargin; - (MASConstraint *)rightMargin; - (MASConstraint *)topMargin; - (MASConstraint *)bottomMargin; - (MASConstraint *)leadingMargin; - (MASConstraint *)trailingMargin; - (MASConstraint *)centerXWithinMargins; - (MASConstraint *)centerYWithinMargins; #endif /** * Sets the constraint debug name */ - (MASConstraint * (^)(id key))key; // NSLayoutConstraint constant Setters // for use outside of mas_updateConstraints/mas_makeConstraints blocks /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight */ - (void)setInsets:(MASEdgeInsets)insets; /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeWidth, NSLayoutAttributeHeight */ - (void)setSizeOffset:(CGSize)sizeOffset; /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY */ - (void)setCenterOffset:(CGPoint)centerOffset; /** * Modifies the NSLayoutConstraint constant */ - (void)setOffset:(CGFloat)offset; // NSLayoutConstraint Installation support #if TARGET_OS_MAC && !TARGET_OS_IPHONE /** * Whether or not to go through the animator proxy when modifying the constraint */ @property (nonatomic, copy, readonly) MASConstraint *animator; #endif /** * Activates an NSLayoutConstraint if it's supported by an OS. * Invokes install otherwise. */ - (void)activate; /** * Deactivates previously installed/activated NSLayoutConstraint. */ - (void)deactivate; /** * Creates a NSLayoutConstraint and adds it to the appropriate view. */ - (void)install; /** * Removes previously installed NSLayoutConstraint */ - (void)uninstall; @end /** * Convenience auto-boxing macros for MASConstraint methods. * * Defining MAS_SHORTHAND_GLOBALS will turn on auto-boxing for default syntax. * A potential drawback of this is that the unprefixed macros will appear in global scope. */ #define mas_equalTo(...) equalTo(MASBoxValue((__VA_ARGS__))) #define mas_greaterThanOrEqualTo(...) greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__))) #define mas_lessThanOrEqualTo(...) lessThanOrEqualTo(MASBoxValue((__VA_ARGS__))) #define mas_offset(...) valueOffset(MASBoxValue((__VA_ARGS__))) #ifdef MAS_SHORTHAND_GLOBALS #define equalTo(...) mas_equalTo(__VA_ARGS__) #define greaterThanOrEqualTo(...) mas_greaterThanOrEqualTo(__VA_ARGS__) #define lessThanOrEqualTo(...) mas_lessThanOrEqualTo(__VA_ARGS__) #define offset(...) mas_offset(__VA_ARGS__) #endif @interface MASConstraint (AutoboxingSupport) /** * Aliases to corresponding relation methods (for shorthand macros) * Also needed to aid autocompletion */ - (MASConstraint * (^)(id attr))mas_equalTo; - (MASConstraint * (^)(id attr))mas_greaterThanOrEqualTo; - (MASConstraint * (^)(id attr))mas_lessThanOrEqualTo; /** * A dummy method to aid autocompletion */ - (MASConstraint * (^)(id offset))mas_offset; @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASConstraint.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,533
```objective-c // // MASCompositeConstraint.m // Masonry // // Created by Jonas Budelmann on 21/07/13. // #import "MASCompositeConstraint.h" #import "MASConstraint+Private.h" @interface MASCompositeConstraint () <MASConstraintDelegate> @property (nonatomic, strong) id mas_key; @property (nonatomic, strong) NSMutableArray *childConstraints; @end @implementation MASCompositeConstraint - (id)initWithChildren:(NSArray *)children { self = [super init]; if (!self) return nil; _childConstraints = [children mutableCopy]; for (MASConstraint *constraint in _childConstraints) { constraint.delegate = self; } return self; } #pragma mark - MASConstraintDelegate - (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { NSUInteger index = [self.childConstraints indexOfObject:constraint]; NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint); [self.childConstraints replaceObjectAtIndex:index withObject:replacementConstraint]; } - (MASConstraint *)constraint:(MASConstraint __unused *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { id<MASConstraintDelegate> strongDelegate = self.delegate; MASConstraint *newConstraint = [strongDelegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; newConstraint.delegate = self; [self.childConstraints addObject:newConstraint]; return newConstraint; } #pragma mark - NSLayoutConstraint multiplier proxies - (MASConstraint * (^)(CGFloat))multipliedBy { return ^id(CGFloat multiplier) { for (MASConstraint *constraint in self.childConstraints) { constraint.multipliedBy(multiplier); } return self; }; } - (MASConstraint * (^)(CGFloat))dividedBy { return ^id(CGFloat divider) { for (MASConstraint *constraint in self.childConstraints) { constraint.dividedBy(divider); } return self; }; } #pragma mark - MASLayoutPriority proxy - (MASConstraint * (^)(MASLayoutPriority))priority { return ^id(MASLayoutPriority priority) { for (MASConstraint *constraint in self.childConstraints) { constraint.priority(priority); } return self; }; } #pragma mark - NSLayoutRelation proxy - (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { return ^id(id attr, NSLayoutRelation relation) { for (MASConstraint *constraint in self.childConstraints.copy) { constraint.equalToWithRelation(attr, relation); } return self; }; } #pragma mark - attribute chaining - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { [self constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; return self; } #pragma mark - Animator proxy #if TARGET_OS_MAC && !TARGET_OS_IPHONE - (MASConstraint *)animator { for (MASConstraint *constraint in self.childConstraints) { [constraint animator]; } return self; } #endif #pragma mark - debug helpers - (MASConstraint * (^)(id))key { return ^id(id key) { self.mas_key = key; int i = 0; for (MASConstraint *constraint in self.childConstraints) { constraint.key([NSString stringWithFormat:@"%@[%d]", key, i++]); } return self; }; } #pragma mark - NSLayoutConstraint constant setters - (void)setInsets:(MASEdgeInsets)insets { for (MASConstraint *constraint in self.childConstraints) { constraint.insets = insets; } } - (void)setOffset:(CGFloat)offset { for (MASConstraint *constraint in self.childConstraints) { constraint.offset = offset; } } - (void)setSizeOffset:(CGSize)sizeOffset { for (MASConstraint *constraint in self.childConstraints) { constraint.sizeOffset = sizeOffset; } } - (void)setCenterOffset:(CGPoint)centerOffset { for (MASConstraint *constraint in self.childConstraints) { constraint.centerOffset = centerOffset; } } #pragma mark - MASConstraint - (void)activate { for (MASConstraint *constraint in self.childConstraints) { [constraint activate]; } } - (void)deactivate { for (MASConstraint *constraint in self.childConstraints) { [constraint deactivate]; } } - (void)install { for (MASConstraint *constraint in self.childConstraints) { constraint.updateExisting = self.updateExisting; [constraint install]; } } - (void)uninstall { for (MASConstraint *constraint in self.childConstraints) { [constraint uninstall]; } } @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASCompositeConstraint.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
982
```objective-c // // Masonry.h // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import <Foundation/Foundation.h> //! Project version number for Masonry. FOUNDATION_EXPORT double MasonryVersionNumber; //! Project version string for Masonry. FOUNDATION_EXPORT const unsigned char MasonryVersionString[]; #import "MASUtilities.h" #import "View+MASAdditions.h" #import "View+MASShorthandAdditions.h" #import "NSArray+MASAdditions.h" #import "NSArray+MASShorthandAdditions.h" #import "MASConstraint.h" #import "MASCompositeConstraint.h" #import "MASViewAttribute.h" #import "MASViewConstraint.h" #import "MASConstraintMaker.h" #import "MASLayoutConstraint.h" #import "NSLayoutConstraint+MASDebugAdditions.h" ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/Masonry.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
168
```objective-c // // NSArray+MASAdditions.h // // // Created by Daniel Hammond on 11/26/13. // // #import "MASUtilities.h" #import "MASConstraintMaker.h" #import "MASViewAttribute.h" @interface NSArray (MASAdditions) /** * Creates a MASConstraintMaker with each view in the callee. * Any constraints defined are added to the view or the appropriate superview once the block has finished executing on each view * * @param block scope within which you can build up the constraints which you wish to apply to each view. * * @return Array of created MASConstraints */ - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block; /** * Creates a MASConstraintMaker with each view in the callee. * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. * If an existing constraint exists then it will be updated instead. * * @param block scope within which you can build up the constraints which you wish to apply to each view. * * @return Array of created/updated MASConstraints */ - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block; /** * Creates a MASConstraintMaker with each view in the callee. * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. * All constraints previously installed for the views will be removed. * * @param block scope within which you can build up the constraints which you wish to apply to each view. * * @return Array of created/updated MASConstraints */ - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block; @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/NSArray+MASAdditions.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
361
```objective-c // // UIView+MASAdditions.h // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASUtilities.h" #import "MASConstraintMaker.h" #import "MASViewAttribute.h" /** * Provides constraint maker block * and convience methods for creating MASViewAttribute which are view + NSLayoutAttribute pairs */ @interface MAS_VIEW (MASAdditions) /** * following properties return a new MASViewAttribute with current view and appropriate NSLayoutAttribute */ @property (nonatomic, strong, readonly) MASViewAttribute *mas_left; @property (nonatomic, strong, readonly) MASViewAttribute *mas_top; @property (nonatomic, strong, readonly) MASViewAttribute *mas_right; @property (nonatomic, strong, readonly) MASViewAttribute *mas_bottom; @property (nonatomic, strong, readonly) MASViewAttribute *mas_leading; @property (nonatomic, strong, readonly) MASViewAttribute *mas_trailing; @property (nonatomic, strong, readonly) MASViewAttribute *mas_width; @property (nonatomic, strong, readonly) MASViewAttribute *mas_height; @property (nonatomic, strong, readonly) MASViewAttribute *mas_centerX; @property (nonatomic, strong, readonly) MASViewAttribute *mas_centerY; @property (nonatomic, strong, readonly) MASViewAttribute *mas_baseline; @property (nonatomic, strong, readonly) MASViewAttribute *(^mas_attribute)(NSLayoutAttribute attr); #if TARGET_OS_IPHONE @property (nonatomic, strong, readonly) MASViewAttribute *mas_leftMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_rightMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_topMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_leadingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_trailingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_centerXWithinMargins; @property (nonatomic, strong, readonly) MASViewAttribute *mas_centerYWithinMargins; #endif /** * a key to associate with this view */ @property (nonatomic, strong) id mas_key; /** * Finds the closest common superview between this view and another view * * @param view other view * * @return returns nil if common superview could not be found */ - (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view; /** * Creates a MASConstraintMaker with the callee view. * Any constraints defined are added to the view or the appropriate superview once the block has finished executing * * @param block scope within which you can build up the constraints which you wish to apply to the view. * * @return Array of created MASConstraints */ - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block; /** * Creates a MASConstraintMaker with the callee view. * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. * If an existing constraint exists then it will be updated instead. * * @param block scope within which you can build up the constraints which you wish to apply to the view. * * @return Array of created/updated MASConstraints */ - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block; /** * Creates a MASConstraintMaker with the callee view. * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. * All constraints previously installed for the view will be removed. * * @param block scope within which you can build up the constraints which you wish to apply to the view. * * @return Array of created/updated MASConstraints */ - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block; @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/View+MASAdditions.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
812
```objective-c // // UIView+MASShorthandAdditions.h // Masonry // // Created by Jonas Budelmann on 22/07/13. // #import "View+MASAdditions.h" #ifdef MAS_SHORTHAND /** * Shorthand view additions without the 'mas_' prefixes, * only enabled if MAS_SHORTHAND is defined */ @interface MAS_VIEW (MASShorthandAdditions) @property (nonatomic, strong, readonly) MASViewAttribute *left; @property (nonatomic, strong, readonly) MASViewAttribute *top; @property (nonatomic, strong, readonly) MASViewAttribute *right; @property (nonatomic, strong, readonly) MASViewAttribute *bottom; @property (nonatomic, strong, readonly) MASViewAttribute *leading; @property (nonatomic, strong, readonly) MASViewAttribute *trailing; @property (nonatomic, strong, readonly) MASViewAttribute *width; @property (nonatomic, strong, readonly) MASViewAttribute *height; @property (nonatomic, strong, readonly) MASViewAttribute *centerX; @property (nonatomic, strong, readonly) MASViewAttribute *centerY; @property (nonatomic, strong, readonly) MASViewAttribute *baseline; @property (nonatomic, strong, readonly) MASViewAttribute *(^attribute)(NSLayoutAttribute attr); #if TARGET_OS_IPHONE @property (nonatomic, strong, readonly) MASViewAttribute *leftMargin; @property (nonatomic, strong, readonly) MASViewAttribute *rightMargin; @property (nonatomic, strong, readonly) MASViewAttribute *topMargin; @property (nonatomic, strong, readonly) MASViewAttribute *bottomMargin; @property (nonatomic, strong, readonly) MASViewAttribute *leadingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *trailingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *centerXWithinMargins; @property (nonatomic, strong, readonly) MASViewAttribute *centerYWithinMargins; #endif - (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; @end #define MAS_ATTR_FORWARD(attr) \ - (MASViewAttribute *)attr { \ return [self mas_##attr]; \ } @implementation MAS_VIEW (MASShorthandAdditions) MAS_ATTR_FORWARD(top); MAS_ATTR_FORWARD(left); MAS_ATTR_FORWARD(bottom); MAS_ATTR_FORWARD(right); MAS_ATTR_FORWARD(leading); MAS_ATTR_FORWARD(trailing); MAS_ATTR_FORWARD(width); MAS_ATTR_FORWARD(height); MAS_ATTR_FORWARD(centerX); MAS_ATTR_FORWARD(centerY); MAS_ATTR_FORWARD(baseline); #if TARGET_OS_IPHONE MAS_ATTR_FORWARD(leftMargin); MAS_ATTR_FORWARD(rightMargin); MAS_ATTR_FORWARD(topMargin); MAS_ATTR_FORWARD(bottomMargin); MAS_ATTR_FORWARD(leadingMargin); MAS_ATTR_FORWARD(trailingMargin); MAS_ATTR_FORWARD(centerXWithinMargins); MAS_ATTR_FORWARD(centerYWithinMargins); #endif - (MASViewAttribute *(^)(NSLayoutAttribute))attribute { return [self mas_attribute]; } - (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_makeConstraints:block]; } - (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_updateConstraints:block]; } - (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_remakeConstraints:block]; } @end #endif ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/View+MASShorthandAdditions.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
704
```objective-c // // UIView+MASAdditions.m // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "View+MASAdditions.h" #import <objc/runtime.h> @implementation MAS_VIEW (MASAdditions) - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block { self.translatesAutoresizingMaskIntoConstraints = NO; MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; block(constraintMaker); return [constraintMaker install]; } - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block { self.translatesAutoresizingMaskIntoConstraints = NO; MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; constraintMaker.updateExisting = YES; block(constraintMaker); return [constraintMaker install]; } - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { self.translatesAutoresizingMaskIntoConstraints = NO; MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; constraintMaker.removeExisting = YES; block(constraintMaker); return [constraintMaker install]; } #pragma mark - NSLayoutAttribute properties - (MASViewAttribute *)mas_left { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeft]; } - (MASViewAttribute *)mas_top { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTop]; } - (MASViewAttribute *)mas_right { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRight]; } - (MASViewAttribute *)mas_bottom { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottom]; } - (MASViewAttribute *)mas_leading { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeading]; } - (MASViewAttribute *)mas_trailing { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailing]; } - (MASViewAttribute *)mas_width { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeWidth]; } - (MASViewAttribute *)mas_height { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeHeight]; } - (MASViewAttribute *)mas_centerX { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterX]; } - (MASViewAttribute *)mas_centerY { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterY]; } - (MASViewAttribute *)mas_baseline { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBaseline]; } - (MASViewAttribute *(^)(NSLayoutAttribute))mas_attribute { return ^(NSLayoutAttribute attr) { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:attr]; }; } #if TARGET_OS_IPHONE - (MASViewAttribute *)mas_leftMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeftMargin]; } - (MASViewAttribute *)mas_rightMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRightMargin]; } - (MASViewAttribute *)mas_topMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTopMargin]; } - (MASViewAttribute *)mas_bottomMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottomMargin]; } - (MASViewAttribute *)mas_leadingMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeadingMargin]; } - (MASViewAttribute *)mas_trailingMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailingMargin]; } - (MASViewAttribute *)mas_centerXWithinMargins { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterXWithinMargins]; } - (MASViewAttribute *)mas_centerYWithinMargins { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterYWithinMargins]; } #endif #pragma mark - associated properties - (id)mas_key { return objc_getAssociatedObject(self, @selector(mas_key)); } - (void)setMas_key:(id)key { objc_setAssociatedObject(self, @selector(mas_key), key, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - heirachy - (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view { MAS_VIEW *closestCommonSuperview = nil; MAS_VIEW *secondViewSuperview = view; while (!closestCommonSuperview && secondViewSuperview) { MAS_VIEW *firstViewSuperview = self; while (!closestCommonSuperview && firstViewSuperview) { if (secondViewSuperview == firstViewSuperview) { closestCommonSuperview = secondViewSuperview; } firstViewSuperview = firstViewSuperview.superview; } secondViewSuperview = secondViewSuperview.superview; } return closestCommonSuperview; } @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/View+MASAdditions.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,029
```objective-c // // MASAttribute.h // Masonry // // Created by Jonas Budelmann on 21/07/13. // #import "MASUtilities.h" /** * An immutable tuple which stores the view and the related NSLayoutAttribute. * Describes part of either the left or right hand side of a constraint equation */ @interface MASViewAttribute : NSObject /** * The view which the reciever relates to */ @property (nonatomic, weak, readonly) MAS_VIEW *view; /** * The attribute which the reciever relates to */ @property (nonatomic, assign, readonly) NSLayoutAttribute layoutAttribute; /** * The designated initializer. */ - (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute; /** * Determine whether the layoutAttribute is a size attribute * * @return YES if layoutAttribute is equal to NSLayoutAttributeWidth or NSLayoutAttributeHeight */ - (BOOL)isSizeAttribute; @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASViewAttribute.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
207
```objective-c // // MASLayoutConstraint.m // Masonry // // Created by Jonas Budelmann on 3/08/13. // #import "MASLayoutConstraint.h" @implementation MASLayoutConstraint @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASLayoutConstraint.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
43
```objective-c // // MASAttribute.m // Masonry // // Created by Jonas Budelmann on 21/07/13. // #import "MASViewAttribute.h" @implementation MASViewAttribute - (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute { self = [super init]; if (!self) return nil; _view = view; _layoutAttribute = layoutAttribute; return self; } - (BOOL)isSizeAttribute { return self.layoutAttribute == NSLayoutAttributeWidth || self.layoutAttribute == NSLayoutAttributeHeight; } - (BOOL)isEqual:(MASViewAttribute *)viewAttribute { if ([viewAttribute isKindOfClass:self.class]) { return self.view == viewAttribute.view && self.layoutAttribute == viewAttribute.layoutAttribute; } return [super isEqual:viewAttribute]; } - (NSUInteger)hash { return MAS_NSUINTROTATE([self.view hash], MAS_NSUINT_BIT / 2) ^ self.layoutAttribute; } @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASViewAttribute.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
218
```objective-c // // MASUtilities.h // Masonry // // Created by Jonas Budelmann on 19/08/13. // #import <Foundation/Foundation.h> #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #define MAS_VIEW UIView #define MASEdgeInsets UIEdgeInsets typedef UILayoutPriority MASLayoutPriority; static const MASLayoutPriority MASLayoutPriorityRequired = UILayoutPriorityRequired; static const MASLayoutPriority MASLayoutPriorityDefaultHigh = UILayoutPriorityDefaultHigh; static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 500; static const MASLayoutPriority MASLayoutPriorityDefaultLow = UILayoutPriorityDefaultLow; static const MASLayoutPriority MASLayoutPriorityFittingSizeLevel = UILayoutPriorityFittingSizeLevel; #elif TARGET_OS_MAC #import <AppKit/AppKit.h> #define MAS_VIEW NSView #define MASEdgeInsets NSEdgeInsets typedef NSLayoutPriority MASLayoutPriority; static const MASLayoutPriority MASLayoutPriorityRequired = NSLayoutPriorityRequired; static const MASLayoutPriority MASLayoutPriorityDefaultHigh = NSLayoutPriorityDefaultHigh; static const MASLayoutPriority MASLayoutPriorityDragThatCanResizeWindow = NSLayoutPriorityDragThatCanResizeWindow; static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 501; static const MASLayoutPriority MASLayoutPriorityWindowSizeStayPut = NSLayoutPriorityWindowSizeStayPut; static const MASLayoutPriority MASLayoutPriorityDragThatCannotResizeWindow = NSLayoutPriorityDragThatCannotResizeWindow; static const MASLayoutPriority MASLayoutPriorityDefaultLow = NSLayoutPriorityDefaultLow; static const MASLayoutPriority MASLayoutPriorityFittingSizeCompression = NSLayoutPriorityFittingSizeCompression; #endif /** * Allows you to attach keys to objects matching the variable names passed. * * view1.mas_key = @"view1", view2.mas_key = @"view2"; * * is equivalent to: * * MASAttachKeys(view1, view2); */ #define MASAttachKeys(...) \ NSDictionary *keyPairs = NSDictionaryOfVariableBindings(__VA_ARGS__); \ for (id key in keyPairs.allKeys) { \ id obj = keyPairs[key]; \ NSAssert([obj respondsToSelector:@selector(setMas_key:)], \ @"Cannot attach mas_key to %@", obj); \ [obj setMas_key:key]; \ } /** * Used to create object hashes * Based on path_to_url */ #define MAS_NSUINT_BIT (CHAR_BIT * sizeof(NSUInteger)) #define MAS_NSUINTROTATE(val, howmuch) ((((NSUInteger)val) << howmuch) | (((NSUInteger)val) >> (MAS_NSUINT_BIT - howmuch))) /** * Given a scalar or struct value, wraps it in NSValue * Based on EXPObjectify: path_to_url */ static inline id _MASBoxValue(const char *type, ...) { va_list v; va_start(v, type); id obj = nil; if (strcmp(type, @encode(id)) == 0) { id actual = va_arg(v, id); obj = actual; } else if (strcmp(type, @encode(CGPoint)) == 0) { CGPoint actual = (CGPoint)va_arg(v, CGPoint); obj = [NSValue value:&actual withObjCType:type]; } else if (strcmp(type, @encode(CGSize)) == 0) { CGSize actual = (CGSize)va_arg(v, CGSize); obj = [NSValue value:&actual withObjCType:type]; } else if (strcmp(type, @encode(MASEdgeInsets)) == 0) { MASEdgeInsets actual = (MASEdgeInsets)va_arg(v, MASEdgeInsets); obj = [NSValue value:&actual withObjCType:type]; } else if (strcmp(type, @encode(double)) == 0) { double actual = (double)va_arg(v, double); obj = [NSNumber numberWithDouble:actual]; } else if (strcmp(type, @encode(float)) == 0) { float actual = (float)va_arg(v, double); obj = [NSNumber numberWithFloat:actual]; } else if (strcmp(type, @encode(int)) == 0) { int actual = (int)va_arg(v, int); obj = [NSNumber numberWithInt:actual]; } else if (strcmp(type, @encode(long)) == 0) { long actual = (long)va_arg(v, long); obj = [NSNumber numberWithLong:actual]; } else if (strcmp(type, @encode(long long)) == 0) { long long actual = (long long)va_arg(v, long long); obj = [NSNumber numberWithLongLong:actual]; } else if (strcmp(type, @encode(short)) == 0) { short actual = (short)va_arg(v, int); obj = [NSNumber numberWithShort:actual]; } else if (strcmp(type, @encode(char)) == 0) { char actual = (char)va_arg(v, int); obj = [NSNumber numberWithChar:actual]; } else if (strcmp(type, @encode(bool)) == 0) { bool actual = (bool)va_arg(v, int); obj = [NSNumber numberWithBool:actual]; } else if (strcmp(type, @encode(unsigned char)) == 0) { unsigned char actual = (unsigned char)va_arg(v, unsigned int); obj = [NSNumber numberWithUnsignedChar:actual]; } else if (strcmp(type, @encode(unsigned int)) == 0) { unsigned int actual = (unsigned int)va_arg(v, unsigned int); obj = [NSNumber numberWithUnsignedInt:actual]; } else if (strcmp(type, @encode(unsigned long)) == 0) { unsigned long actual = (unsigned long)va_arg(v, unsigned long); obj = [NSNumber numberWithUnsignedLong:actual]; } else if (strcmp(type, @encode(unsigned long long)) == 0) { unsigned long long actual = (unsigned long long)va_arg(v, unsigned long long); obj = [NSNumber numberWithUnsignedLongLong:actual]; } else if (strcmp(type, @encode(unsigned short)) == 0) { unsigned short actual = (unsigned short)va_arg(v, unsigned int); obj = [NSNumber numberWithUnsignedShort:actual]; } va_end(v); return obj; } #define MASBoxValue(value) _MASBoxValue(@encode(__typeof__((value))), (value)) ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASUtilities.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,404
```objective-c // // MASConstraint+Private.h // Masonry // // Created by Nick Tymchenko on 29/04/14. // #import "MASConstraint.h" @protocol MASConstraintDelegate; @interface MASConstraint () /** * Whether or not to check for an existing constraint instead of adding constraint */ @property (nonatomic, assign) BOOL updateExisting; /** * Usually MASConstraintMaker but could be a parent MASConstraint */ @property (nonatomic, weak) id<MASConstraintDelegate> delegate; /** * Based on a provided value type, is equal to calling: * NSNumber - setOffset: * NSValue with CGPoint - setPointOffset: * NSValue with CGSize - setSizeOffset: * NSValue with MASEdgeInsets - setInsets: */ - (void)setLayoutConstantWithValue:(NSValue *)value; @end @interface MASConstraint (Abstract) /** * Sets the constraint relation to given NSLayoutRelation * returns a block which accepts one of the following: * MASViewAttribute, UIView, NSValue, NSArray * see readme for more details. */ - (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation; /** * Override to set a custom chaining behaviour */ - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; @end @protocol MASConstraintDelegate <NSObject> /** * Notifies the delegate when the constraint needs to be replaced with another constraint. For example * A MASViewConstraint may turn into a MASCompositeConstraint when an array is passed to one of the equality blocks */ - (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint; - (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASConstraint+Private.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
381
```objective-c // // NSArray+MASAdditions.m // // // Created by Daniel Hammond on 11/26/13. // // #import "NSArray+MASAdditions.h" #import "View+MASAdditions.h" @implementation NSArray (MASAdditions) - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block { NSMutableArray *constraints = [NSMutableArray array]; for (MAS_VIEW *view in self) { NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); [constraints addObjectsFromArray:[view mas_makeConstraints:block]]; } return constraints; } - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block { NSMutableArray *constraints = [NSMutableArray array]; for (MAS_VIEW *view in self) { NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); [constraints addObjectsFromArray:[view mas_updateConstraints:block]]; } return constraints; } - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { NSMutableArray *constraints = [NSMutableArray array]; for (MAS_VIEW *view in self) { NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); [constraints addObjectsFromArray:[view mas_remakeConstraints:block]]; } return constraints; } @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/NSArray+MASAdditions.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
288
```objective-c // // MASConstraint.h // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASViewAttribute.h" #import "MASConstraint.h" #import "MASLayoutConstraint.h" #import "MASUtilities.h" /** * A single constraint. * Contains the attributes neccessary for creating a NSLayoutConstraint and adding it to the appropriate view */ @interface MASViewConstraint : MASConstraint <NSCopying> /** * First item/view and first attribute of the NSLayoutConstraint */ @property (nonatomic, strong, readonly) MASViewAttribute *firstViewAttribute; /** * Second item/view and second attribute of the NSLayoutConstraint */ @property (nonatomic, strong, readonly) MASViewAttribute *secondViewAttribute; /** * initialises the MASViewConstraint with the first part of the equation * * @param firstViewAttribute view.mas_left, view.mas_width etc. * * @return a new view constraint */ - (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute; /** * Returns all MASViewConstraints installed with this view as a first item. * * @param view A view to retrieve constraints for. * * @return An array of MASViewConstraints. */ + (NSArray *)installedConstraintsForView:(MAS_VIEW *)view; @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASViewConstraint.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
274
```objective-c // // NSArray+MASShorthandAdditions.h // Masonry // // Created by Jonas Budelmann on 22/07/13. // #import "NSArray+MASAdditions.h" #ifdef MAS_SHORTHAND /** * Shorthand array additions without the 'mas_' prefixes, * only enabled if MAS_SHORTHAND is defined */ @interface NSArray (MASShorthandAdditions) - (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; @end @implementation NSArray (MASShorthandAdditions) - (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_makeConstraints:block]; } - (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_updateConstraints:block]; } - (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_remakeConstraints:block]; } @end #endif ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/NSArray+MASShorthandAdditions.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
219
```objective-c // // MASConstraint.m // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASViewConstraint.h" #import "MASConstraint+Private.h" #import "MASCompositeConstraint.h" #import "MASLayoutConstraint.h" #import "View+MASAdditions.h" #import <objc/runtime.h> @interface MAS_VIEW (MASConstraints) @property (nonatomic, readonly) NSMutableSet *mas_installedConstraints; @end @implementation MAS_VIEW (MASConstraints) static char kInstalledConstraintsKey; - (NSMutableSet *)mas_installedConstraints { NSMutableSet *constraints = objc_getAssociatedObject(self, &kInstalledConstraintsKey); if (!constraints) { constraints = [NSMutableSet set]; objc_setAssociatedObject(self, &kInstalledConstraintsKey, constraints, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } return constraints; } @end @interface MASViewConstraint () @property (nonatomic, strong, readwrite) MASViewAttribute *secondViewAttribute; @property (nonatomic, weak) MAS_VIEW *installedView; @property (nonatomic, weak) MASLayoutConstraint *layoutConstraint; @property (nonatomic, assign) NSLayoutRelation layoutRelation; @property (nonatomic, assign) MASLayoutPriority layoutPriority; @property (nonatomic, assign) CGFloat layoutMultiplier; @property (nonatomic, assign) CGFloat layoutConstant; @property (nonatomic, assign) BOOL hasLayoutRelation; @property (nonatomic, strong) id mas_key; @property (nonatomic, assign) BOOL useAnimator; @end @implementation MASViewConstraint - (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute { self = [super init]; if (!self) return nil; _firstViewAttribute = firstViewAttribute; self.layoutPriority = MASLayoutPriorityRequired; self.layoutMultiplier = 1; return self; } #pragma mark - NSCoping - (id)copyWithZone:(NSZone __unused *)zone { MASViewConstraint *constraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:self.firstViewAttribute]; constraint.layoutConstant = self.layoutConstant; constraint.layoutRelation = self.layoutRelation; constraint.layoutPriority = self.layoutPriority; constraint.layoutMultiplier = self.layoutMultiplier; constraint.delegate = self.delegate; return constraint; } #pragma mark - Public + (NSArray *)installedConstraintsForView:(MAS_VIEW *)view { return [view.mas_installedConstraints allObjects]; } #pragma mark - Private - (void)setLayoutConstant:(CGFloat)layoutConstant { _layoutConstant = layoutConstant; #if TARGET_OS_MAC && !TARGET_OS_IPHONE if (self.useAnimator) { [self.layoutConstraint.animator setConstant:layoutConstant]; } else { self.layoutConstraint.constant = layoutConstant; } #else self.layoutConstraint.constant = layoutConstant; #endif } - (void)setLayoutRelation:(NSLayoutRelation)layoutRelation { _layoutRelation = layoutRelation; self.hasLayoutRelation = YES; } - (BOOL)supportsActiveProperty { return [self.layoutConstraint respondsToSelector:@selector(isActive)]; } - (BOOL)isActive { BOOL active = YES; if ([self supportsActiveProperty]) { active = [self.layoutConstraint isActive]; } return active; } - (BOOL)hasBeenInstalled { return (self.layoutConstraint != nil) && [self isActive]; } - (void)setSecondViewAttribute:(id)secondViewAttribute { if ([secondViewAttribute isKindOfClass:NSValue.class]) { [self setLayoutConstantWithValue:secondViewAttribute]; } else if ([secondViewAttribute isKindOfClass:MAS_VIEW.class]) { _secondViewAttribute = [[MASViewAttribute alloc] initWithView:secondViewAttribute layoutAttribute:self.firstViewAttribute.layoutAttribute]; } else if ([secondViewAttribute isKindOfClass:MASViewAttribute.class]) { _secondViewAttribute = secondViewAttribute; } else { NSAssert(NO, @"attempting to add unsupported attribute: %@", secondViewAttribute); } } #pragma mark - NSLayoutConstraint multiplier proxies - (MASConstraint * (^)(CGFloat))multipliedBy { return ^id(CGFloat multiplier) { NSAssert(!self.hasBeenInstalled, @"Cannot modify constraint multiplier after it has been installed"); self.layoutMultiplier = multiplier; return self; }; } - (MASConstraint * (^)(CGFloat))dividedBy { return ^id(CGFloat divider) { NSAssert(!self.hasBeenInstalled, @"Cannot modify constraint multiplier after it has been installed"); self.layoutMultiplier = 1.0/divider; return self; }; } #pragma mark - MASLayoutPriority proxy - (MASConstraint * (^)(MASLayoutPriority))priority { return ^id(MASLayoutPriority priority) { NSAssert(!self.hasBeenInstalled, @"Cannot modify constraint priority after it has been installed"); self.layoutPriority = priority; return self; }; } #pragma mark - NSLayoutRelation proxy - (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { return ^id(id attribute, NSLayoutRelation relation) { if ([attribute isKindOfClass:NSArray.class]) { NSAssert(!self.hasLayoutRelation, @"Redefinition of constraint relation"); NSMutableArray *children = NSMutableArray.new; for (id attr in attribute) { MASViewConstraint *viewConstraint = [self copy]; viewConstraint.secondViewAttribute = attr; [children addObject:viewConstraint]; } MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; compositeConstraint.delegate = self.delegate; [self.delegate constraint:self shouldBeReplacedWithConstraint:compositeConstraint]; return compositeConstraint; } else { NSAssert(!self.hasLayoutRelation || self.layoutRelation == relation && [attribute isKindOfClass:NSValue.class], @"Redefinition of constraint relation"); self.layoutRelation = relation; self.secondViewAttribute = attribute; return self; } }; } #pragma mark - Semantic properties - (MASConstraint *)with { return self; } - (MASConstraint *)and { return self; } #pragma mark - attribute chaining - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { NSAssert(!self.hasLayoutRelation, @"Attributes should be chained before defining the constraint relation"); return [self.delegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; } #pragma mark - Animator proxy #if TARGET_OS_MAC && !TARGET_OS_IPHONE - (MASConstraint *)animator { self.useAnimator = YES; return self; } #endif #pragma mark - debug helpers - (MASConstraint * (^)(id))key { return ^id(id key) { self.mas_key = key; return self; }; } #pragma mark - NSLayoutConstraint constant setters - (void)setInsets:(MASEdgeInsets)insets { NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; switch (layoutAttribute) { case NSLayoutAttributeLeft: case NSLayoutAttributeLeading: self.layoutConstant = insets.left; break; case NSLayoutAttributeTop: self.layoutConstant = insets.top; break; case NSLayoutAttributeBottom: self.layoutConstant = -insets.bottom; break; case NSLayoutAttributeRight: case NSLayoutAttributeTrailing: self.layoutConstant = -insets.right; break; default: break; } } - (void)setOffset:(CGFloat)offset { self.layoutConstant = offset; } - (void)setSizeOffset:(CGSize)sizeOffset { NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; switch (layoutAttribute) { case NSLayoutAttributeWidth: self.layoutConstant = sizeOffset.width; break; case NSLayoutAttributeHeight: self.layoutConstant = sizeOffset.height; break; default: break; } } - (void)setCenterOffset:(CGPoint)centerOffset { NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; switch (layoutAttribute) { case NSLayoutAttributeCenterX: self.layoutConstant = centerOffset.x; break; case NSLayoutAttributeCenterY: self.layoutConstant = centerOffset.y; break; default: break; } } #pragma mark - MASConstraint - (void)activate { if ([self supportsActiveProperty] && self.layoutConstraint) { if (self.hasBeenInstalled) { return; } self.layoutConstraint.active = YES; [self.firstViewAttribute.view.mas_installedConstraints addObject:self]; } else { [self install]; } } - (void)deactivate { if ([self supportsActiveProperty]) { self.layoutConstraint.active = NO; [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; } else { [self uninstall]; } } - (void)install { if (self.hasBeenInstalled) { return; } MAS_VIEW *firstLayoutItem = self.firstViewAttribute.view; NSLayoutAttribute firstLayoutAttribute = self.firstViewAttribute.layoutAttribute; MAS_VIEW *secondLayoutItem = self.secondViewAttribute.view; NSLayoutAttribute secondLayoutAttribute = self.secondViewAttribute.layoutAttribute; // alignment attributes must have a secondViewAttribute // therefore we assume that is refering to superview // eg make.left.equalTo(@10) if (!self.firstViewAttribute.isSizeAttribute && !self.secondViewAttribute) { secondLayoutItem = firstLayoutItem.superview; secondLayoutAttribute = firstLayoutAttribute; } MASLayoutConstraint *layoutConstraint = [MASLayoutConstraint constraintWithItem:firstLayoutItem attribute:firstLayoutAttribute relatedBy:self.layoutRelation toItem:secondLayoutItem attribute:secondLayoutAttribute multiplier:self.layoutMultiplier constant:self.layoutConstant]; layoutConstraint.priority = self.layoutPriority; layoutConstraint.mas_key = self.mas_key; if (secondLayoutItem) { MAS_VIEW *closestCommonSuperview = [firstLayoutItem mas_closestCommonSuperview:secondLayoutItem]; NSAssert(closestCommonSuperview, @"couldn't find a common superview for %@ and %@", firstLayoutItem, secondLayoutItem); self.installedView = closestCommonSuperview; } else { self.installedView = firstLayoutItem; } MASLayoutConstraint *existingConstraint = nil; if (self.updateExisting) { existingConstraint = [self layoutConstraintSimilarTo:layoutConstraint]; } if (existingConstraint) { // just update the constant existingConstraint.constant = layoutConstraint.constant; self.layoutConstraint = existingConstraint; } else { [self.installedView addConstraint:layoutConstraint]; self.layoutConstraint = layoutConstraint; [firstLayoutItem.mas_installedConstraints addObject:self]; } } - (MASLayoutConstraint *)layoutConstraintSimilarTo:(MASLayoutConstraint *)layoutConstraint { // check if any constraints are the same apart from the only mutable property constant // go through constraints in reverse as we do not want to match auto-resizing or interface builder constraints // and they are likely to be added first. for (NSLayoutConstraint *existingConstraint in self.installedView.constraints.reverseObjectEnumerator) { if (![existingConstraint isKindOfClass:MASLayoutConstraint.class]) continue; if (existingConstraint.firstItem != layoutConstraint.firstItem) continue; if (existingConstraint.secondItem != layoutConstraint.secondItem) continue; if (existingConstraint.firstAttribute != layoutConstraint.firstAttribute) continue; if (existingConstraint.secondAttribute != layoutConstraint.secondAttribute) continue; if (existingConstraint.relation != layoutConstraint.relation) continue; if (existingConstraint.multiplier != layoutConstraint.multiplier) continue; if (existingConstraint.priority != layoutConstraint.priority) continue; return (id)existingConstraint; } return nil; } - (void)uninstall { [self.installedView removeConstraint:self.layoutConstraint]; self.layoutConstraint = nil; self.installedView = nil; [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASViewConstraint.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
2,540
```objective-c // // NSLayoutConstraint+MASDebugAdditions.h // Masonry // // Created by Jonas Budelmann on 3/08/13. // #import "MASUtilities.h" /** * makes debug and log output of NSLayoutConstraints more readable */ @interface NSLayoutConstraint (MASDebugAdditions) @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/NSLayoutConstraint+MASDebugAdditions.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
67
```objective-c // // MASConstraint.m // Masonry // // Created by Nick Tymchenko on 1/20/14. // #import "MASConstraint.h" #import "MASConstraint+Private.h" #define MASMethodNotImplemented() \ @throw [NSException exceptionWithName:NSInternalInconsistencyException \ reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", NSStringFromSelector(_cmd)] \ userInfo:nil] @implementation MASConstraint #pragma mark - Init - (id)init { NSAssert(![self isMemberOfClass:[MASConstraint class]], @"MASConstraint is an abstract class, you should not instantiate it directly."); return [super init]; } #pragma mark - NSLayoutRelation proxies - (MASConstraint * (^)(id))equalTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationEqual); }; } - (MASConstraint * (^)(id))mas_equalTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationEqual); }; } - (MASConstraint * (^)(id))greaterThanOrEqualTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); }; } - (MASConstraint * (^)(id))mas_greaterThanOrEqualTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); }; } - (MASConstraint * (^)(id))lessThanOrEqualTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); }; } - (MASConstraint * (^)(id))mas_lessThanOrEqualTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); }; } #pragma mark - MASLayoutPriority proxies - (MASConstraint * (^)())priorityLow { return ^id{ self.priority(MASLayoutPriorityDefaultLow); return self; }; } - (MASConstraint * (^)())priorityMedium { return ^id{ self.priority(MASLayoutPriorityDefaultMedium); return self; }; } - (MASConstraint * (^)())priorityHigh { return ^id{ self.priority(MASLayoutPriorityDefaultHigh); return self; }; } #pragma mark - NSLayoutConstraint constant proxies - (MASConstraint * (^)(MASEdgeInsets))insets { return ^id(MASEdgeInsets insets){ self.insets = insets; return self; }; } - (MASConstraint * (^)(CGSize))sizeOffset { return ^id(CGSize offset) { self.sizeOffset = offset; return self; }; } - (MASConstraint * (^)(CGPoint))centerOffset { return ^id(CGPoint offset) { self.centerOffset = offset; return self; }; } - (MASConstraint * (^)(CGFloat))offset { return ^id(CGFloat offset){ self.offset = offset; return self; }; } - (MASConstraint * (^)(NSValue *value))valueOffset { return ^id(NSValue *offset) { NSAssert([offset isKindOfClass:NSValue.class], @"expected an NSValue offset, got: %@", offset); [self setLayoutConstantWithValue:offset]; return self; }; } - (MASConstraint * (^)(id offset))mas_offset { // Will never be called due to macro return nil; } #pragma mark - NSLayoutConstraint constant setter - (void)setLayoutConstantWithValue:(NSValue *)value { if ([value isKindOfClass:NSNumber.class]) { self.offset = [(NSNumber *)value doubleValue]; } else if (strcmp(value.objCType, @encode(CGPoint)) == 0) { CGPoint point; [value getValue:&point]; self.centerOffset = point; } else if (strcmp(value.objCType, @encode(CGSize)) == 0) { CGSize size; [value getValue:&size]; self.sizeOffset = size; } else if (strcmp(value.objCType, @encode(MASEdgeInsets)) == 0) { MASEdgeInsets insets; [value getValue:&insets]; self.insets = insets; } else { NSAssert(NO, @"attempting to set layout constant with unsupported value: %@", value); } } #pragma mark - Semantic properties - (MASConstraint *)with { return self; } - (MASConstraint *)and { return self; } #pragma mark - Chaining - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute __unused)layoutAttribute { MASMethodNotImplemented(); } - (MASConstraint *)left { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; } - (MASConstraint *)top { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; } - (MASConstraint *)right { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; } - (MASConstraint *)bottom { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; } - (MASConstraint *)leading { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; } - (MASConstraint *)trailing { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; } - (MASConstraint *)width { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; } - (MASConstraint *)height { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; } - (MASConstraint *)centerX { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; } - (MASConstraint *)centerY { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; } - (MASConstraint *)baseline { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; } #if TARGET_OS_IPHONE - (MASConstraint *)leftMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; } - (MASConstraint *)rightMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; } - (MASConstraint *)topMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; } - (MASConstraint *)bottomMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; } - (MASConstraint *)leadingMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; } - (MASConstraint *)trailingMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; } - (MASConstraint *)centerXWithinMargins { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; } - (MASConstraint *)centerYWithinMargins { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; } #endif #pragma mark - Abstract - (MASConstraint * (^)(CGFloat multiplier))multipliedBy { MASMethodNotImplemented(); } - (MASConstraint * (^)(CGFloat divider))dividedBy { MASMethodNotImplemented(); } - (MASConstraint * (^)(MASLayoutPriority priority))priority { MASMethodNotImplemented(); } - (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { MASMethodNotImplemented(); } - (MASConstraint * (^)(id key))key { MASMethodNotImplemented(); } - (void)setInsets:(MASEdgeInsets __unused)insets { MASMethodNotImplemented(); } - (void)setSizeOffset:(CGSize __unused)sizeOffset { MASMethodNotImplemented(); } - (void)setCenterOffset:(CGPoint __unused)centerOffset { MASMethodNotImplemented(); } - (void)setOffset:(CGFloat __unused)offset { MASMethodNotImplemented(); } #if TARGET_OS_MAC && !TARGET_OS_IPHONE - (MASConstraint *)animator { MASMethodNotImplemented(); } #endif - (void)activate { MASMethodNotImplemented(); } - (void)deactivate { MASMethodNotImplemented(); } - (void)install { MASMethodNotImplemented(); } - (void)uninstall { MASMethodNotImplemented(); } @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASConstraint.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,660
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * Created by james <path_to_url on 9/28/11. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageDecoder.h" @implementation UIImage (ForceDecode) + (UIImage *)decodedImageWithImage:(UIImage *)image { if (image.images) { // Do not decode animated images return image; } CGImageRef imageRef = image.CGImage; CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || infoMask == kCGImageAlphaNoneSkipFirst || infoMask == kCGImageAlphaNoneSkipLast); // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. // path_to_url#qa/qa1037/_index.html if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { // Unset the old alpha info. bitmapInfo &= ~kCGBitmapAlphaInfoMask; // Set noneSkipFirst. bitmapInfo |= kCGImageAlphaNoneSkipFirst; } // Some PNGs tell us they have alpha but only 3 components. Odd. else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { // Unset the old alpha info. bitmapInfo &= ~kCGBitmapAlphaInfoMask; bitmapInfo |= kCGImageAlphaPremultipliedFirst; } // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. CGContextRef context = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, CGImageGetBitsPerComponent(imageRef), 0, colorSpace, bitmapInfo); CGColorSpaceRelease(colorSpace); // If failed, return undecompressed image if (!context) return image; CGContextDrawImage(context, imageRect, imageRef); CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); CGContextRelease(context); UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; CGImageRelease(decompressedImageRef); return decompressedImage; } @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageDecoder.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
601
```objective-c // // MASConstraintBuilder.h // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASConstraint.h" #import "MASUtilities.h" typedef NS_OPTIONS(NSInteger, MASAttribute) { MASAttributeLeft = 1 << NSLayoutAttributeLeft, MASAttributeRight = 1 << NSLayoutAttributeRight, MASAttributeTop = 1 << NSLayoutAttributeTop, MASAttributeBottom = 1 << NSLayoutAttributeBottom, MASAttributeLeading = 1 << NSLayoutAttributeLeading, MASAttributeTrailing = 1 << NSLayoutAttributeTrailing, MASAttributeWidth = 1 << NSLayoutAttributeWidth, MASAttributeHeight = 1 << NSLayoutAttributeHeight, MASAttributeCenterX = 1 << NSLayoutAttributeCenterX, MASAttributeCenterY = 1 << NSLayoutAttributeCenterY, MASAttributeBaseline = 1 << NSLayoutAttributeBaseline, #if TARGET_OS_IPHONE MASAttributeLeftMargin = 1 << NSLayoutAttributeLeftMargin, MASAttributeRightMargin = 1 << NSLayoutAttributeRightMargin, MASAttributeTopMargin = 1 << NSLayoutAttributeTopMargin, MASAttributeBottomMargin = 1 << NSLayoutAttributeBottomMargin, MASAttributeLeadingMargin = 1 << NSLayoutAttributeLeadingMargin, MASAttributeTrailingMargin = 1 << NSLayoutAttributeTrailingMargin, MASAttributeCenterXWithinMargins = 1 << NSLayoutAttributeCenterXWithinMargins, MASAttributeCenterYWithinMargins = 1 << NSLayoutAttributeCenterYWithinMargins, #endif }; /** * Provides factory methods for creating MASConstraints. * Constraints are collected until they are ready to be installed * */ @interface MASConstraintMaker : NSObject /** * The following properties return a new MASViewConstraint * with the first item set to the makers associated view and the appropriate MASViewAttribute */ @property (nonatomic, strong, readonly) MASConstraint *left; @property (nonatomic, strong, readonly) MASConstraint *top; @property (nonatomic, strong, readonly) MASConstraint *right; @property (nonatomic, strong, readonly) MASConstraint *bottom; @property (nonatomic, strong, readonly) MASConstraint *leading; @property (nonatomic, strong, readonly) MASConstraint *trailing; @property (nonatomic, strong, readonly) MASConstraint *width; @property (nonatomic, strong, readonly) MASConstraint *height; @property (nonatomic, strong, readonly) MASConstraint *centerX; @property (nonatomic, strong, readonly) MASConstraint *centerY; @property (nonatomic, strong, readonly) MASConstraint *baseline; #if TARGET_OS_IPHONE @property (nonatomic, strong, readonly) MASConstraint *leftMargin; @property (nonatomic, strong, readonly) MASConstraint *rightMargin; @property (nonatomic, strong, readonly) MASConstraint *topMargin; @property (nonatomic, strong, readonly) MASConstraint *bottomMargin; @property (nonatomic, strong, readonly) MASConstraint *leadingMargin; @property (nonatomic, strong, readonly) MASConstraint *trailingMargin; @property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins; @property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins; #endif /** * Returns a block which creates a new MASCompositeConstraint with the first item set * to the makers associated view and children corresponding to the set bits in the * MASAttribute parameter. Combine multiple attributes via binary-or. */ @property (nonatomic, strong, readonly) MASConstraint *(^attributes)(MASAttribute attrs); /** * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeEdges * which generates the appropriate MASViewConstraint children (top, left, bottom, right) * with the first item set to the makers associated view */ @property (nonatomic, strong, readonly) MASConstraint *edges; /** * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeSize * which generates the appropriate MASViewConstraint children (width, height) * with the first item set to the makers associated view */ @property (nonatomic, strong, readonly) MASConstraint *size; /** * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeCenter * which generates the appropriate MASViewConstraint children (centerX, centerY) * with the first item set to the makers associated view */ @property (nonatomic, strong, readonly) MASConstraint *center; /** * Whether or not to check for an existing constraint instead of adding constraint */ @property (nonatomic, assign) BOOL updateExisting; /** * Whether or not to remove existing constraints prior to installing */ @property (nonatomic, assign) BOOL removeExisting; /** * initialises the maker with a default view * * @param view any MASConstrait are created with this view as the first item * * @return a new MASConstraintMaker */ - (id)initWithView:(MAS_VIEW *)view; /** * Calls install method on any MASConstraints which have been created by this maker * * @return an array of all the installed MASConstraints */ - (NSArray *)install; - (MASConstraint * (^)(dispatch_block_t))group; @end ```
/content/code_sandbox/WeChat/ThirdLib/Masonry/MASConstraintMaker.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,086
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIView+WebCacheOperation.h" #import "objc/runtime.h" static char loadOperationKey; @implementation UIView (WebCacheOperation) - (NSMutableDictionary *)operationDictionary { NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); if (operations) { return operations; } operations = [NSMutableDictionary dictionary]; objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); return operations; } - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key { [self sd_cancelImageLoadOperationWithKey:key]; NSMutableDictionary *operationDictionary = [self operationDictionary]; [operationDictionary setObject:operation forKey:key]; } - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key { // Cancel in progress downloader from queue NSMutableDictionary *operationDictionary = [self operationDictionary]; id operations = [operationDictionary objectForKey:key]; if (operations) { if ([operations isKindOfClass:[NSArray class]]) { for (id <SDWebImageOperation> operation in operations) { if (operation) { [operation cancel]; } } } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ [(id<SDWebImageOperation>) operations cancel]; } [operationDictionary removeObjectForKey:key]; } } - (void)sd_removeImageLoadOperationWithKey:(NSString *)key { NSMutableDictionary *operationDictionary = [self operationDictionary]; [operationDictionary removeObjectForKey:key]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIView+WebCacheOperation.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
382
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <UIKit/UIKit.h> #import "SDWebImageManager.h" @interface UIView (WebCacheOperation) /** * Set the image load operation (storage in a UIView based dictionary) * * @param operation the operation * @param key key for storing the operation */ - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key; /** * Cancel all operations for the current UIView and key * * @param key key for identifying the operations */ - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key; /** * Just remove the operations corresponding to the current UIView and key without cancelling them * * @param key key for identifying the operations */ - (void)sd_removeImageLoadOperationWithKey:(NSString *)key; @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIView+WebCacheOperation.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
225
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> @protocol SDWebImageOperation <NSObject> - (void)cancel; @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageOperation.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
78
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIImageView+HighlightedWebCache.h" #import "UIView+WebCacheOperation.h" #define UIImageViewHighlightedWebCacheOperationKey @"highlightedImage" @implementation UIImageView (HighlightedWebCache) - (void)sd_setHighlightedImageWithURL:(NSURL *)url { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; } - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; } - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; } - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; } - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { [self sd_cancelCurrentHighlightedImageLoad]; if (url) { __weak UIImageView *wself = self; id<SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!wself) return; dispatch_main_sync_safe (^ { if (!wself) return; if (image) { wself.highlightedImage = image; [wself setNeedsLayout]; } if (completedBlock && finished) { completedBlock(image, error, cacheType, url); } }); }]; [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey]; } else { dispatch_main_async_safe(^{ NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; if (completedBlock) { completedBlock(nil, error, SDImageCacheTypeNone, url); } }); } } - (void)sd_cancelCurrentHighlightedImageLoad { [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey]; } @end @implementation UIImageView (HighlightedWebCacheDeprecated) - (void)setHighlightedImageWithURL:(NSURL *)url { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; } - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; } - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:0 progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)cancelCurrentHighlightedImageLoad { [self sd_cancelCurrentHighlightedImageLoad]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIImageView+HighlightedWebCache.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
959
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Jamie Pinkham * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <TargetConditionals.h> #ifdef __OBJC_GC__ #error SDWebImage does not support Objective-C Garbage Collection #endif #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 #error SDWebImage doesn't support Deployement Target version < 5.0 #endif #if !TARGET_OS_IPHONE #import <AppKit/AppKit.h> #ifndef UIImage #define UIImage NSImage #endif #ifndef UIImageView #define UIImageView NSImageView #endif #else #import <UIKit/UIKit.h> #endif #ifndef NS_ENUM #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type #endif #ifndef NS_OPTIONS #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type #endif #if OS_OBJECT_USE_OBJC #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) #define SDDispatchQueueSetterSementics strong #else #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) (dispatch_release(q)) #define SDDispatchQueueSetterSementics assign #endif extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); typedef void(^SDWebImageNoParamsBlock)(); #define dispatch_main_sync_safe(block)\ if ([NSThread isMainThread]) {\ block();\ } else {\ dispatch_sync(dispatch_get_main_queue(), block);\ } #define dispatch_main_async_safe(block)\ if ([NSThread isMainThread]) {\ block();\ } else {\ dispatch_async(dispatch_get_main_queue(), block);\ } ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageCompat.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
437
```objective-c // // Created by Fabrice Aneche on 06/01/14. // #import <Foundation/Foundation.h> @interface NSData (ImageContentType) /** * Compute the content type for an image data * * @param data the input data * * @return the content type as string (i.e. image/jpeg, image/gif) */ + (NSString *)sd_contentTypeForImageData:(NSData *)data; @end @interface NSData (ImageContentTypeDeprecated) + (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`"); @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/NSData+ImageContentType.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
123
```objective-c // // Created by Fabrice Aneche on 06/01/14. // #import "NSData+ImageContentType.h" @implementation NSData (ImageContentType) + (NSString *)sd_contentTypeForImageData:(NSData *)data { uint8_t c; [data getBytes:&c length:1]; switch (c) { case 0xFF: return @"image/jpeg"; case 0x89: return @"image/png"; case 0x47: return @"image/gif"; case 0x49: case 0x4D: return @"image/tiff"; case 0x52: // R as RIFF for WEBP if ([data length] < 12) { return nil; } NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { return @"image/webp"; } return nil; } return nil; } @end @implementation NSData (ImageContentTypeDeprecated) + (NSString *)contentTypeForImageData:(NSData *)data { return [self sd_contentTypeForImageData:data]; } @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/NSData+ImageContentType.m
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
271
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" typedef NS_ENUM(NSInteger, SDImageCacheType) { /** * The image wasn't available the SDWebImage caches, but was downloaded from the web. */ SDImageCacheTypeNone, /** * The image was obtained from the disk cache. */ SDImageCacheTypeDisk, /** * The image was obtained from the memory cache. */ SDImageCacheTypeMemory }; typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); /** * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed * asynchronous so it doesnt add unnecessary latency to the UI. */ @interface SDImageCache : NSObject /** * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory. * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. */ @property (assign, nonatomic) BOOL shouldDecompressImages; /** * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. */ @property (assign, nonatomic) NSUInteger maxMemoryCost; /** * The maximum length of time to keep an image in the cache, in seconds */ @property (assign, nonatomic) NSInteger maxCacheAge; /** * The maximum size of the cache, in bytes. */ @property (assign, nonatomic) NSUInteger maxCacheSize; /** * Returns global shared cache instance * * @return SDImageCache global instance */ + (SDImageCache *)sharedImageCache; /** * Init a new cache store with a specific namespace * * @param ns The namespace to use for this cache store */ - (id)initWithNamespace:(NSString *)ns; /** * Add a read-only cache path to search for images pre-cached by SDImageCache * Useful if you want to bundle pre-loaded images with your app * * @param path The path to use for this read-only cache path */ - (void)addReadOnlyCachePath:(NSString *)path; /** * Store an image into memory and disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL */ - (void)storeImage:(UIImage *)image forKey:(NSString *)key; /** * Store an image into memory and optionally disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES */ - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; /** * Store an image into memory and optionally disk cache at the given key. * * @param image The image to store * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage * @param imageData The image data as returned by the server, this representation will be used for disk storage * instead of converting the given image object into a storable/compressed image format in order * to save quality and CPU * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES */ - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; /** * Query the disk cache asynchronously. * * @param key The unique key used to store the wanted image */ - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; /** * Query the memory cache synchronously. * * @param key The unique key used to store the wanted image */ - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; /** * Query the disk cache synchronously after checking the memory cache. * * @param key The unique key used to store the wanted image */ - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; /** * Remove the image from memory and disk cache synchronously * * @param key The unique image cache key */ - (void)removeImageForKey:(NSString *)key; /** * Remove the image from memory and disk cache synchronously * * @param key The unique image cache key * @param completion An block that should be executed after the image has been removed (optional) */ - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; /** * Remove the image from memory and optionally disk cache synchronously * * @param key The unique image cache key * @param fromDisk Also remove cache entry from disk if YES */ - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; /** * Remove the image from memory and optionally disk cache synchronously * * @param key The unique image cache key * @param fromDisk Also remove cache entry from disk if YES * @param completion An block that should be executed after the image has been removed (optional) */ - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; /** * Clear all memory cached images */ - (void)clearMemory; /** * Clear all disk cached images. Non-blocking method - returns immediately. * @param completion An block that should be executed after cache expiration completes (optional) */ - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; /** * Clear all disk cached images * @see clearDiskOnCompletion: */ - (void)clearDisk; /** * Remove all expired cached image from disk. Non-blocking method - returns immediately. * @param completionBlock An block that should be executed after cache expiration completes (optional) */ - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; /** * Remove all expired cached image from disk * @see cleanDiskWithCompletionBlock: */ - (void)cleanDisk; /** * Get the size used by the disk cache */ - (NSUInteger)getSize; /** * Get the number of images in the disk cache */ - (NSUInteger)getDiskCount; /** * Asynchronously calculate the disk cache's size. */ - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; /** * Async check if image exists in disk cache already (does not load the image) * * @param key the key describing the url * @param completionBlock the block to be executed when the check is done. * @note the completion block will be always executed on the main queue */ - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; /** * Check if image exists in disk cache already (does not load the image) * * @param key the key describing the url * * @return YES if an image exists for the given key */ - (BOOL)diskImageExistsWithKey:(NSString *)key; /** * Get the cache path for a certain key (needs the cache path root folder) * * @param key the key (can be obtained from url using cacheKeyForURL) * @param path the cach path root folder * * @return the cache path */ - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; /** * Get the default cache path for a certain key * * @param key the key (can be obtained from url using cacheKeyForURL) * * @return the default cache path */ - (NSString *)defaultCachePathForKey:(NSString *)key; - (float)checkTmpSize; @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDImageCache.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,783
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageManager.h" @class SDWebImagePrefetcher; @protocol SDWebImagePrefetcherDelegate <NSObject> @optional /** * Called when an image was prefetched. * * @param imagePrefetcher The current image prefetcher * @param imageURL The image url that was prefetched * @param finishedCount The total number of images that were prefetched (successful or not) * @param totalCount The total number of images that were to be prefetched */ - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; /** * Called when all images are prefetched. * @param imagePrefetcher The current image prefetcher * @param totalCount The total number of images that were prefetched (whether successful or not) * @param skippedCount The total number of images that were skipped */ - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; @end typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); /** * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. */ @interface SDWebImagePrefetcher : NSObject /** * The web image manager */ @property (strong, nonatomic, readonly) SDWebImageManager *manager; /** * Maximum number of URLs to prefetch at the same time. Defaults to 3. */ @property (nonatomic, assign) NSUInteger maxConcurrentDownloads; /** * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. */ @property (nonatomic, assign) SDWebImageOptions options; /** * Queue options for Prefetcher. Defaults to Main Queue. */ @property (nonatomic, assign) dispatch_queue_t prefetcherQueue; @property (weak, nonatomic) id <SDWebImagePrefetcherDelegate> delegate; /** * Return the global image prefetcher instance. */ + (SDWebImagePrefetcher *)sharedImagePrefetcher; /** * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, * currently one image is downloaded at a time, * and skips images for failed downloads and proceed to the next image in the list * * @param urls list of URLs to prefetch */ - (void)prefetchURLs:(NSArray *)urls; /** * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, * currently one image is downloaded at a time, * and skips images for failed downloads and proceed to the next image in the list * * @param urls list of URLs to prefetch * @param progressBlock block to be called when progress updates; * first parameter is the number of completed (successful or not) requests, * second parameter is the total number of images originally requested to be prefetched * @param completionBlock block to be called when prefetching is completed * first param is the number of completed (successful or not) requests, * second parameter is the number of skipped requests */ - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; /** * Remove and cancel queued list */ - (void)cancelPrefetching; @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImagePrefetcher.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
827
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" #import "SDWebImageOperation.h" typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { SDWebImageDownloaderLowPriority = 1 << 0, SDWebImageDownloaderProgressiveDownload = 1 << 1, /** * By default, request prevent the of NSURLCache. With this flag, NSURLCache * is used with default policies. */ SDWebImageDownloaderUseNSURLCache = 1 << 2, /** * Call completion block with nil image/imageData if the image was read from NSURLCache * (to be combined with `SDWebImageDownloaderUseNSURLCache`). */ SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, /** * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for * extra time in background to let the request finish. If the background task expires the operation will be cancelled. */ SDWebImageDownloaderContinueInBackground = 1 << 4, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; */ SDWebImageDownloaderHandleCookies = 1 << 5, /** * Enable to allow untrusted SSL ceriticates. * Useful for testing purposes. Use with caution in production. */ SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, /** * Put the image in the high priority queue. */ SDWebImageDownloaderHighPriority = 1 << 7, }; typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { /** * Default value. All download operations will execute in queue style (first-in-first-out). */ SDWebImageDownloaderFIFOExecutionOrder, /** * All download operations will execute in stack style (last-in-first-out). */ SDWebImageDownloaderLIFOExecutionOrder }; extern NSString *const SDWebImageDownloadStartNotification; extern NSString *const SDWebImageDownloadStopNotification; typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); /** * Asynchronous downloader dedicated and optimized for image loading. */ @interface SDWebImageDownloader : NSObject /** * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory. * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. */ @property (assign, nonatomic) BOOL shouldDecompressImages; @property (assign, nonatomic) NSInteger maxConcurrentDownloads; /** * Shows the current amount of downloads that still need to be downloaded */ @property (readonly, nonatomic) NSUInteger currentDownloadCount; /** * The timeout value (in seconds) for the download operation. Default: 15.0. */ @property (assign, nonatomic) NSTimeInterval downloadTimeout; /** * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. */ @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; /** * Singleton method, returns the shared instance * * @return global shared instance of downloader class */ + (SDWebImageDownloader *)sharedDownloader; /** * Set username */ @property (strong, nonatomic) NSString *username; /** * Set password */ @property (strong, nonatomic) NSString *password; /** * Set filter to pick headers for downloading image HTTP request. * * This block will be invoked for each downloading image request, returned * NSDictionary will be used as headers in corresponding HTTP request. */ @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; /** * Set a value for a HTTP header to be appended to each download HTTP request. * * @param value The value for the header field. Use `nil` value to remove the header. * @param field The name of the header field to set. */ - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; /** * Returns the value of the specified HTTP header field. * * @return The value associated with the header field field, or `nil` if there is no corresponding header field. */ - (NSString *)valueForHTTPHeaderField:(NSString *)field; /** * Sets a subclass of `SDWebImageDownloaderOperation` as the default * `NSOperation` to be used each time SDWebImage constructs a request * operation to download an image. * * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. */ - (void)setOperationClass:(Class)operationClass; /** * Creates a SDWebImageDownloader async downloader instance with a given URL * * The delegate will be informed when the image is finish downloaded or an error has happen. * * @see SDWebImageDownloaderDelegate * * @param url The URL to the image to download * @param options The options to be used for this download * @param progressBlock A block called repeatedly while the image is downloading * @param completedBlock A block called once the download is completed. * If the download succeeded, the image parameter is set, in case of error, * error parameter is set with the error. The last parameter is always YES * if SDWebImageDownloaderProgressiveDownload isn't use. With the * SDWebImageDownloaderProgressiveDownload option, this block is called * repeatedly with the partial image object and the finished argument set to NO * before to be called a last time with the full image and finished argument * set to YES. In case of error, the finished argument is always YES. * * @return A cancellable SDWebImageOperation */ - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock; /** * Sets the download queue suspension state */ - (void)setSuspended:(BOOL)suspended; @end ```
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageDownloader.h
objective-c
2016-06-06T01:53:42
2024-08-05T09:45:48
WeChat
zhengwenming/WeChat
1,626
1,410