<强>前言:强>
适用场景:商城类的应用。将自定义的购物车视图设置为navigationItem的导航栏按钮。效果图如下:
<>强实现原理:强>
1,利用navigationItem可以将UIView设置为导航栏的按钮;
2,将一个UIButton和一个UILabel添加到一个UIView上,然后将这个UIView设置为navigationItem的右侧按钮;3,UILabel控件的动画效果。
<强>具体实现代码如下:& # 8203;强>
#进口 @protocol ShopCarButtonDelegate & lt; & lt;/span> NSObject>//代理的方法,在此方法内,完成按钮的点击事件。 - (void) shopCarButtonClickAction; @end @interfaceShopCarView: UIView @ property(原子,分配)id<& lt;/span> ShopCarButtonDelegate>委托;//为购物车设置角标内数的值 - (void) setShopCarCount: (NSString *)数; @end >之前
& # 8203;#进口“ShopCarView.h” @interfaceShopCarView () @ property(原子、强)UIButton * carButton; @ property(原子、强)UILabel * countLabel; @end @ implementation ShopCarView - (instancetype) initWithFrame:(CGRect中){帧 CGRect中myFrame=CGRectMake(0, 0, 40岁,40); 自我=[superinitWithFrame myFrame):; 如果(自我){ [selfaddSubview: self.carButton]; } returnself; } ——(UIButton *) carButton { 如果(! _carButton) { _carButton=[UIButtonbuttonWithType UIButtonTypeCustom):; _carButton.frame=CGRectMake(32 0, 8日,32); [_carButtonsetImage: [UIImageimageNamed: @”购物1”)forState: UIControlStateNormal); [_carButtonaddTarget:作用:@ selector (shopCarButtonAction) forControlEvents: UIControlEventTouchUpInside); } return_carButton; } ——(UILabel *) countLabel { 如果(! _countLabel) { _countLabel=[[UILabelalloc] initWithFrame: CGRectMake(16) 24日5日16日]; _countLabel。写成backgroundColor=[UIColorredColor]; _countLabel。textAlignment=NSTextAlignmentCenter; _countLabel。输入textColor=[UIColorwhiteColor]; _countLabel.layer。cornerRadius=8; _countLabel。字体=(UIFontsystemFontOfSize: 12); _countLabel.layer。masksToBounds=是的; [selfaddSubview: _countLabel]; } return_countLabel; }//为购物车设置角标内数的值 - (void) setShopCarCount: {(NSString *)计数 如果([count integerValue]==0) { 如果(_countLabel) { [_countLabelremoveFromSuperview]; _countLabel=零; } 返回; } 如果(计数integerValue祝辞9){ self.countLabel。文本=@“9 +”; 其他}{ self.countLabel。文本=计数; } [selfshakeView: _countLabel]; }//实现的代理方法 - (void) shopCarButtonAction { [self.delegateshopCarButtonClickAction]; }//实现抖动效果 - (void) shakeView: viewToShake (UIView *) { CGFloat t=2.0; CGAffineTransform translateRight=CGAffineTransformTranslate (CGAffineTransformIdentity t、0.0); CGAffineTransform translateLeft=CGAffineTransformTranslate (CGAffineTransformIdentity、- t、0.0); viewToShake。变换=translateLeft; (延迟UIViewanimateWithDuration: 0.07: 0.0选项:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeatanimations: ^ { (UIViewsetAnimationRepeatCount: 2.0); viewToShake。变换=translateRight; }完成:^ (BOOL完成){ 如果(完成){ (延迟UIViewanimateWithDuration: 0.05: 0.0选项:UIViewAnimationOptionBeginFromCurrentStateanimations: ^ { viewToShake。变换=CGAffineTransformIdentity; }完成:零); } }); } @end >之前& # 8203;代码很简单,逻辑也比较清晰。使用代理方法,将自定义的观点的属性隐藏起来,打到很好的封装效果。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
iOS实现自定义购物车角标显示购物数量(添加商品时角标抖动Vie)