NSCollectionView 实现选中效果

来源:互联网 发布:阿里手机小号软件 编辑:程序博客网 时间:2024/04/29 09:30

(一)实现选中,并对View添加效果:

1:首先需要设置NSCollectionView允许选中。

可以在IB里面选中CollectionView 后勾选selectable,或者直接代码设置可以勾选

[_collectionView setSelectable:YES];

2:对NSCollectionViewItem的View进行重画,添加一个是否选中的属性

@interface AlexNSCollectionViewItemView :NSView

{

   BOOL _isSelected;

}

@property (nonatomic,assign)BOOL isSelected;



@implementation AlexNSCollectionViewItemView

@synthesize isSelected =_isSelected;


- (id)initWithFrame:(NSRect)frame

{

   self = [superinitWithFrame:frame];

   if (self) {

        // Initialization code here.

    }

    return self;

}


- (void)drawRect:(NSRect)dirtyRect

{

   NSRect imageRect =NSMakeRect(5,5,self.frame.size.width -10,self.frame.size.height -10);

    

   NSBezierPath* imageRoundedRectanglePath = [NSBezierPathbezierPathWithRoundedRect:imageRectxRadius: 4 yRadius: 4];

   NSColor* fillColor =nil;

   NSColor* strokeColor =nil;

    

    //默认是未选中的

    if (_isSelected) {

        

        fillColor = [NSColorcolorWithCalibratedRed:0.851green:0.851blue:0.851alpha:1];

        strokeColor = [NSColorcolorWithCalibratedRed:0.408 green:0.592 blue:0.855 alpha:1];

     

    }else{


        fillColor = [NSColorclearColor];

        strokeColor = [NSColorcolorWithCalibratedRed:0.749 green:0.749 blue:0.749 alpha:1];

    }

    

    [fillColorsetFill];

    [imageRoundedRectanglePathfill];

    [strokeColorsetStroke];


    [superdrawRect:dirtyRect];

}


- (void)setIsSelected:(BOOL)isSelected

{

   _isSelected = isSelected;

    [selfsetNeedsDisplay:YES];

}


3:重写NSCollectionViewItem的selected方法

@interface ALExNSCollectionVIewItem :NSCollectionViewItem


@end


@implementation ALExNSCollectionVIewItem


- (void)setSelected:(BOOL)selected

{

    [(AlexNSCollectionViewItemView *)[selfview]setIsSelected:selected];

    [supersetSelected:selected];

}


4:然后将重写的类在IB中设置到相应的控件的Class上。允许程序,点击鼠标选中,就能看到选中效果了。Good Luck!





0 0
原创粉丝点击