tableView

来源:互联网 发布:知乎 电动牙刷 编辑:程序博客网 时间:2024/05/29 02:34
////  DMViewController.h//  DMFilterView////  Created by Thomas Ricouard on 19/04/13.//  Copyright (c) 2013 Thomas Ricouard. All rights reserved.// #import <uikit uikit.h="">#import "DMFilterView.h" @interface DMViewController : UIViewController <dmfilterviewdelegate, uitableviewdatasource,="" uitableviewdelegate=""> @property (nonatomic, strong) DMFilterView *filterView;@property (nonatomic, strong) UITableView *tableView;@end


////  DMViewController.m//  DMFilterView////  Created by Thomas Ricouard on 19/04/13.//  Copyright (c) 2013 Thomas Ricouard. All rights reserved.// #import "DMViewController.h" @interface DMViewController ()@end @implementation DMViewController - (void)viewDidLoad{    [super viewDidLoad];    _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];    [self.tableView setDelegate:self];    [self.tableView setDataSource:self];    [self.view addSubview:self.tableView];    _filterView = [[DMFilterView alloc]initWithStrings:@[@"ABC", @"Filter 1", @"Filter 2"] containerView:self.view];    [self.filterView attachToContainerView];    [self.filterView setDelegate:self];         // Do any additional setup after loading the view, typically from a nib.} - (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.} #pragma mark - UITableView Datasource - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {    return 1;} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    return 50;} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    static NSString *cellIdentifier = @"Cell";         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];         if(cell == nil) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];    }    if (indexPath.row == 0) {        cell.textLabel.text = @"Default style";    }    else if (indexPath.row == 1){        cell.textLabel.text = @"Images style";    }    else if (indexPath.row == 2){        cell.textLabel.text = @"Colors style";    }    else{      cell.textLabel.text = @"SCROOOOL";    }         return cell;} #pragma mark - UITableView Delegate methods - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    [tableView deselectRowAtIndexPath:indexPath animated:YES];    if (indexPath.row == 0) {        [self.filterView applyDefaultStyle];        [self.filterView setDraggable:YES];    }    else if (indexPath.row == 1){        [self.filterView setSelectedItemBackgroundImage:[UIImage imageNamed:@"tabbar_select"]];        [self.filterView setBackgroundImage:[UIImage imageNamed:@"tabbar"]];        UIColor *mColor = [UIColor colorWithRed:240/255.0                                          green:130/255.0                                           blue:76/255.0                                          alpha:1.0];        [self.filterView setTitlesColor:mColor];        [self.filterView setTitlesFont:[UIFont systemFontOfSize:14]];        [self.filterView setTitleInsets:UIEdgeInsetsMake(7, 0, 0, 0)];        [self.filterView setDraggable:YES];    }    else if (indexPath.row == 2){        [self.filterView setSelectedItemTopBackgroundColor:[UIColor grayColor]];        [self.filterView setSelectedItemTopBackroundColorHeight:5];        [self.filterView setSelectedItemBackgroundColor:[UIColor lightGrayColor]];        [self.filterView setBackgroundColor:[UIColor underPageBackgroundColor]];        [self.filterView setTitlesFont:[UIFont boldSystemFontOfSize:19]];        [self.filterView setTitlesColor:[UIColor blueColor]];        [self.filterView setTitleInsets:UIEdgeInsetsMake(0, 0, 0, 0)];        [self.filterView setDraggable:NO];    }} #pragma mark - ScrollView delegate- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {    [self.filterView hide:YES animated:YES animationCompletion:^{             }];} - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{    [self.filterView hide:NO animated:YES animationCompletion:^{     }];} #pragma mark - FilterVie delegate- (void)filterView:(DMFilterView *)filterView didSelectedAtIndex:(NSInteger)index{    NSLog(@"%d", index);} - (CGFloat )filterViewSelectionAnimationSpeed:(DMFilterView *)filterView{    //return the default value as example, you don't have to implement this delegate    //if you don't want to modify the selection speed    //Or you can return 0.0 to disable the animation totally    return kAnimationSpeed;}  @end

////  DMAppDelegate.h//  DMFilterView////  Created by Thomas Ricouard on 19/04/13.//  Copyright (c) 2013 Thomas Ricouard. All rights reserved.// #import <uikit uikit.h=""> @class DMViewController; @interface DMAppDelegate : UIResponder <uiapplicationdelegate> @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) DMViewController *viewController; @end

////  DMAppDelegate.m//  DMFilterView////  Created by Thomas Ricouard on 19/04/13.//  Copyright (c) 2013 Thomas Ricouard. All rights reserved.// #import "DMAppDelegate.h" #import "DMViewController.h" @implementation DMAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    // Override point for customization after application launch.    self.viewController = [[DMViewController alloc] initWithNibName:@"DMViewController" bundle:nil];    self.window.rootViewController = self.viewController;    [self.window makeKeyAndVisible];    return YES;} - (void)applicationWillResignActive:(UIApplication *)application{    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.} - (void)applicationDidEnterBackground:(UIApplication *)application{    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.} - (void)applicationWillEnterForeground:(UIApplication *)application{    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.} - (void)applicationDidBecomeActive:(UIApplication *)application{    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.} - (void)applicationWillTerminate:(UIApplication *)application{    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.} @end


////  MSFilterViewController.h//  MySeeen////  Created by Thomas Ricouard on 19/04/13.//// #import <uikit uikit.h=""> extern const CGFloat kFilterViewHeight;extern const CGFloat kAnimationSpeed; @class DMFilterView;@protocol DMFilterViewDelegate <nsobject>@required//The delegare must implement this method to perform actions regarding the newly selected index- (void)filterView:(DMFilterView *)filterView didSelectedAtIndex:(NSInteger)index;@optional//If the delegate implement this method it can return a custom animation speed for the hide/unhide- (CGFloat)filterViewDisplayAnimatioSpeed:(DMFilterView *)filterView;//If the delegate implement this methid it can return a custom animation speed for the selection- (CGFloat)filterViewSelectionAnimationSpeed:(DMFilterView *)filterView;//Implement this method to know when the selection animation begin- (void)filterViewSelectionAnimationDidBegin:(DMFilterView *)filterView;//Implement this method to know when the selection animation end- (void)filterViewSelectionAnimationDidEnd:(DMFilterView *)filterView;@end @interface DMFilterView : UIView{    id<dmfilterviewdelegate>__unsafe_unretained _delegate;} //When the selectedIndex is set the selected button will change with animation//Delegate will be calles as usual//You can change the selected buttom programatically instead of a user action, it will behave the same@property (nonatomic) NSInteger selectedIndex;@property (nonatomic, unsafe_unretained) id<dmfilterviewdelegate>delegate;@property (nonatomic, readonly, assign) UIView *containerView;//You can set a background image, the background image will remove the background color.@property (nonatomic, strong) UIImage *backgroundImage;//The selected background image behind the selected button.//The selected background color is set to nil if you set an image@property (nonatomic, strong) UIImage *selectedItemBackgroundImage;//The selected background color behind the selected button//The selected background image is set to nil if you set a color@property (nonatomic, strong) UIColor *selectedItemBackgroundColor;//The selected background color at the top of the selected item//Is set to nil if you set a selected backround image@property (nonatomic, strong) UIColor *selectedItemTopBackgroundColor;//The selected background top color height;//Default value is 5@property (nonatomic) CGFloat selectedItemTopBackroundColorHeight;//The buttons title color@property (nonatomic, strong) UIColor *titlesColor;//The buttons font@property (nonatomic, strong) UIFont *titlesFont;//The inset of the title@property (nonatomic) UIEdgeInsets titleInsets; //Is the selected button is draggable. Default is YES.@property (nonatomic, getter = isDraggable) BOOL draggable; /**Designated initializer@param strings An array of strings containing titles of buttons. Maximum number of titles, and so of buttons is 4 An exception will be raised if you pass more than 4 string@param containerView The view where the filter view will be added, can't be changed once set@return An initialized MSFilterView  */- (id)initWithStrings:(NSArray *)strings       containerView:(UIView *)contrainerView;/**You should called this method once to attach the filter view to the  bottom of the view you passed in the init method */- (void)attachToContainerView;/**Hide and show the filter view, with or without animation@param hide if YES it will hide the filter view, if NO if will show the filter view@param animated animate or not the transition @param completion A completion block which is called at the end of the show/hide animation */- (void)hide:(BOOL)hide    animated:(BOOL)animated    animationCompletion:(void (^)(void))completion; /** Provide a basic default style, this style is automaticcaly set after yout initialized DMFilter If for any reasons you want to restore the default style, you can use this method Basically reset images, font and insets property */- (void)applyDefaultStyle; /** @param index the button index @return the title of the button at the given index */- (NSString *)titleAtIndex:(NSInteger)index;/** @param title the new title will replace the previous title @param index the button index */- (void)setTitle:(NSString *)title atIndex:(NSInteger)index;@end

////  MSFilterViewController.m//  MySeeen////  Created by Thomas Ricouard on 19/04/13.//// #import "DMFilterView.h"#import <quartzcore quartzcore.h=""> const CGFloat kFilterViewHeight = 44.0;const CGFloat kAnimationSpeed = 0.20;@interface DMFilterView (){    NSMutableArray *_strings;    CGPoint _initialDraggingPoint;}@property (nonatomic, strong) UIImageView *backgroundView;@property (nonatomic, strong) UIView *selectedBackgroundView;@property (nonatomic, strong) UIImageView *selectedBackgroundImageView;@property (nonatomic, strong) UIView *selectedTopBackgroundView;@property (nonatomic, strong) UIPanGestureRecognizer *panGesture; - (void)updateButtonsStyle;- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer;- (void)pan:(UIPanGestureRecognizer *)reconizer;- (NSArray *)buttonsIntersectForFrame:(CGRect)frame;- (UIButton *)selectedButton;@end @implementation DMFilterView - (id)initWithStrings:(NSArray *)strings containerView:(UIView *)contrainerView{    NSAssert(strings.count <= 4, @"only support less than 4 titles");    self = [super initWithFrame:CGRectMake(0,                                           contrainerView.frame.size.height -                                           kFilterViewHeight,                                           contrainerView.frame.size.width,                                           kFilterViewHeight)];    if (self) {        _strings = [strings mutableCopy];        _containerView = contrainerView;        _backgroundView = [[UIImageView alloc]initWithFrame:self.bounds];        [self addSubview:self.backgroundView];        CGFloat x = 0.0;        CGFloat buttonWidth = self.frame.size.width/strings.count;        NSInteger tag = 0;        _selectedBackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0,                                                                          0,                                                                          buttonWidth,                                                                          self.frame.size.height)];        _selectedBackgroundImageView = [[UIImageView alloc]initWithFrame:self.selectedBackgroundView.frame];        [self.selectedBackgroundView addSubview:self.selectedBackgroundImageView];        _selectedTopBackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0,                                                                             0,                                                                             self.selectedBackgroundView.frame.size.width,                                                                             5)];        [self.selectedBackgroundView addSubview:self.selectedTopBackgroundView];        [self addSubview:self.selectedBackgroundView];        for (NSString *string in strings) {            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];            [button setTag:tag];            [button setFrame:CGRectMake(x,                                        0,                                        buttonWidth,                                        self.frame.size.height)];            [button setTitle:string forState:UIControlStateNormal];            [button addTarget:self                       action:@selector(onButton:)             forControlEvents:UIControlEventTouchUpInside];            [self addSubview:button];            x += buttonWidth;            tag += 1;        }    }    [self applyDefaultStyle];    [self setDraggable:YES];    [self setSelectedIndex:0];    return self;} #pragma mark - display- (void)attachToContainerView{    if (!self.superview) {        [self.containerView addSubview:self];       }} - (void)applyDefaultStyle{    //Default ugly style    [self setBackgroundColor:[UIColor lightGrayColor]];    [self setSelectedItemBackgroundColor:[UIColor darkGrayColor]];    [self setSelectedItemTopBackgroundColor:[UIColor blueColor]];    [self setTitlesColor:[UIColor blackColor]];    [self setTitleInsets:UIEdgeInsetsMake(0, 0, 0, 0)];    [self setTitlesFont:[UIFont systemFontOfSize:14]];} - (void)hide:(BOOL)hide animated:(BOOL)animated animationCompletion:(void (^)(void))completion{    CGRect f = self.frame;    if (!hide) {        f.origin.y = self.containerView.frame.size.height - kFilterViewHeight;     }    else{        f.origin.y = self.containerView.frame.size.height + kFilterViewHeight;    }    if (animated) {        CGFloat animationSpeed;        if ([self.delegate respondsToSelector:@selector(filterViewDisplayAnimatioSpeed:)]) {            animationSpeed = [self.delegate filterViewDisplayAnimatioSpeed:self];        }        else{            animationSpeed = kAnimationSpeed;        }        [UIView animateWithDuration:animationSpeed                              delay:0.0                            options:UIViewAnimationOptionCurveEaseOut                         animations:^{                             [self setFrame:f];                         } completion:^(BOOL finished) {                             if (finished) {                                 completion();                             }                         }];    }    else{        [self setFrame:f];        completion();    } } #pragma mark - Action- (void)onButton:(id)sender{    UIButton *button = (UIButton *)sender;    for (UIButton *btn in self.subviews) {        if ([btn isKindOfClass:[UIButton class]]) {            if ([button isEqual:btn]) {                [btn setUserInteractionEnabled:NO];            }            else{                [btn setUserInteractionEnabled:YES];            }        }    }    CGFloat animationSpeed;    if ([self.delegate respondsToSelector:@selector(filterViewSelectionAnimationSpeed:)]) {        animationSpeed = [self.delegate filterViewSelectionAnimationSpeed:self];    }    else{        animationSpeed = kAnimationSpeed;    }    if ([self.delegate respondsToSelector:         @selector(filterViewSelectionAnimationDidBegin:)]) {        [self.delegate         filterViewSelectionAnimationDidBegin:self];    }    [UIView animateWithDuration:animationSpeed                          delay:0.0                        options:UIViewAnimationOptionCurveEaseOut                     animations:^{                         CGRect frame = self.selectedBackgroundView.frame;                         frame.origin.x = button.frame.origin.x;                         [self.selectedBackgroundView setFrame:frame];                     } completion:^(BOOL finished) {                         if (finished) {                             if ([self.delegate                                  respondsToSelector:@selector(filterViewSelectionAnimationDidEnd:)]) {                                 [self.delegate                                  filterViewSelectionAnimationDidEnd:self];                             }                         }                     }];    _selectedIndex = button.tag;    [self.delegate filterView:self didSelectedAtIndex:_selectedIndex];} - (void)setSelectedIndex:(NSInteger)selectedIndex{    NSAssert(selectedIndex < _strings.count, @"requested index is out of bounds");    UIButton *selectedButton;    for (UIButton *button in self.subviews) {        if ([button isKindOfClass:[UIButton class]]) {            if (button.tag == selectedIndex) {                selectedButton = button;                break;            }        }    }    [self onButton:selectedButton];} #pragma mark - Background- (void)setBackgroundImage:(UIImage *)backgroundImage{    _backgroundImage = backgroundImage;    [self.backgroundView setImage:_backgroundImage];} - (void)setBackgroundColor:(UIColor *)backgroundColor{    self.backgroundView.image = nil;    [super setBackgroundColor:backgroundColor];} - (void)setSelectedItemBackgroundImage:(UIImage *)selectedItemBackgroundImage{    self.selectedItemBackgroundColor = nil;    self.selectedTopBackgroundView.backgroundColor = nil;    [self.selectedBackgroundImageView setImage:selectedItemBackgroundImage];    _selectedItemBackgroundImage = selectedItemBackgroundImage;} - (void)setSelectedItemBackgroundColor:(UIColor *)selectedItemBackgroundColor{    self.selectedBackgroundImageView.image = nil;    [self.selectedBackgroundView setBackgroundColor:selectedItemBackgroundColor];    _selectedItemBackgroundColor = selectedItemBackgroundColor;} - (void)setSelectedItemTopBackgroundColor:(UIColor *)selectedItemTopBackgroundColor{    [self.selectedTopBackgroundView setBackgroundColor:selectedItemTopBackgroundColor];    _selectedItemTopBackgroundColor = selectedItemTopBackgroundColor;} - (void)setSelectedItemTopBackroundColorHeight:(CGFloat)selectedItemTopBacktroundColorHeight{    CGRect frame = self.selectedTopBackgroundView.frame;    frame.size.height = selectedItemTopBacktroundColorHeight;    [self.selectedTopBackgroundView setFrame:frame];    _selectedItemTopBackroundColorHeight = selectedItemTopBacktroundColorHeight;} - (void)setTitleInsets:(UIEdgeInsets)titleInsets{    for (UIButton *button in self.subviews) {        if ([button isKindOfClass:[UIButton class]]) {            [button setTitleEdgeInsets:titleInsets];        }    }    _titleInsets = titleInsets;} #pragma mark - internal properti- (UIButton *)selectedButton{    for (UIButton *button in self.subviews) {        if ([button isKindOfClass:[UIButton class]]) {            if (button.tag == self.selectedIndex) {                return button;            }        }    }    return nil;} - (void)setSelectedButton:(UIButton *)button{    [self setSelectedIndex:button.tag];} #pragma mark - buttons style- (void)setTitlesColor:(UIColor *)titlesColor{    _titlesColor = titlesColor;    [self updateButtonsStyle];} - (void)setTitlesFont:(UIFont *)titlesFont{    _titlesFont = titlesFont;    [self updateButtonsStyle];} - (void)updateButtonsStyle{    for (UIButton *button in self.subviews) {        if ([button isKindOfClass:[UIButton class]]) {            [button setTitleColor:self.titlesColor forState:UIControlStateNormal];            [button.titleLabel setFont:self.titlesFont];        }    }} #pragma mark - strings- (NSString *)titleAtIndex:(NSInteger)index{    NSAssert(index < _strings.count, @"requested index is out of bounds");    return [_strings objectAtIndex:index];} - (void)setTitle:(NSString *)title atIndex:(NSInteger)index{    NSAssert(index < _strings.count, @"requested index is out of bounds");    [_strings replaceObjectAtIndex:index withObject:title];    for (UIButton *button in self.subviews) {        if ([button isKindOfClass:[UIButton class]]) {            if (button.tag == index) {                [button setTitle:title forState:UIControlStateNormal];                break;            }        }    }} #pragma mark - Pan gesture- (void)setDraggable:(BOOL)draggable{    _draggable = draggable;    if (draggable) {        _panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];        [self.selectedBackgroundView addGestureRecognizer:self.panGesture];        [self.selectedBackgroundView setUserInteractionEnabled:YES];    }    else{        [self.selectedBackgroundView removeGestureRecognizer:self.panGesture];        [self.selectedBackgroundView setUserInteractionEnabled:NO];    }}- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer{    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {        UIView *piece = gestureRecognizer.view;        CGPoint locationInView = [gestureRecognizer locationInView:piece];        CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];                 piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);        piece.center = locationInSuperview;    }} - (void)pan:(UIPanGestureRecognizer *)reconizer{    [self adjustAnchorPointForGestureRecognizer:reconizer];         if (reconizer.state == UIGestureRecognizerStateBegan) {        _initialDraggingPoint = self.selectedBackgroundView.layer.position;             }    else if (reconizer.state == UIGestureRecognizerStateChanged){        CGPoint translation = [reconizer translationInView:[self.selectedBackgroundView superview]];        CGFloat correctedTranslation = translation.x;        [self.selectedBackgroundView setCenter:CGPointMake([self.selectedBackgroundView center].x +                                                           correctedTranslation,                                                           [self.selectedBackgroundView center].y)];        [reconizer setTranslation:CGPointZero inView:[self.selectedBackgroundView superview]];             }    else if (reconizer.state == UIGestureRecognizerStateEnded || reconizer.state == UIGestureRecognizerStateCancelled){        NSArray *buttons = [self buttonsIntersectForFrame:self.selectedBackgroundView.frame];        if (buttons.count == 1) {            [self setSelectedButton:[buttons objectAtIndex:0]];        }        else{            CGRect firstIntersection = CGRectIntersection(self.selectedBackgroundView.frame, [[buttons objectAtIndex:0]frame]);            CGRect secondIntersection = CGRectIntersection(self.selectedBackgroundView.frame, [[buttons objectAtIndex:1]frame]);            if (firstIntersection.size.width < secondIntersection.size.width) {                [self setSelectedButton:[buttons objectAtIndex:1]];            }            else{                [self setSelectedButton:[buttons objectAtIndex:0]];            }        }    }} - (NSArray *)buttonsIntersectForFrame:(CGRect)frame{    NSMutableArray *intersections = [[NSMutableArray alloc]initWithCapacity:2];    for (UIButton *button in self.subviews) {        if ([button isKindOfClass:[UIButton class]]) {            BOOL intersect = CGRectIntersectsRect(button.frame, frame);            if (intersect) {                [intersections addObject:button];            }            intersect = NO;        }    }    return intersections;} @end



结果

0 0