天天看点

【深入浅出IOS开发】彩票-重写按钮控件

①创建子类继承UIButton,然后关联相应的UIButton控件

②重写initWithCoder 和 initWithFrame里面设置同样的代码,确保不管是通过代码还是xib,storyborad来创建Button都会执行

③重写titleRectForContentRect和imgeRectForContentRect

[objc]  view plain copy

  1. #import "MJTitleButton.h"  
  2. #import <Availability.h>  
  3. @interface MJTitleButton()  
  4. @property (nonatomic, strong) UIFont *titleFont;  
  5. @end  
  6. // initWithCoder  --->  awakeFromNib  
  7. @implementation MJTitleButton  
  8. - (id)initWithCoder:(NSCoder *)decoder  
  9. {  
  10.     if (self = [super initWithCoder:decoder]) {  
  11.         [self setup];  
  12.     }  
  13.     return self;  
  14. }  
  15. - (id)initWithFrame:(CGRect)frame  
  16. {  
  17.     if (self = [super initWithFrame:frame]) {  
  18.         [self setup];  
  19.     }  
  20.     return self;  
  21. }  
  22. - (void)setup  
  23. {  
  24.     self.titleFont = [UIFont systemFontOfSize:14];  
  25.     self.titleLabel.font = self.titleFont;  
  26.     // 图标居中  
  27.     self.imageView.contentMode = UIViewContentModeCenter;  
  28. }  
  29. - (CGRect)titleRectForContentRect:(CGRect)contentRect  
  30. {  
  31.     CGFloat titleX = 0;  
  32.     CGFloat titleY = 0;  
  33.     NSDictionary *attrs = @{NSFontAttributeName : self.titleFont};  
  34.     CGFloat titleW;  
  35.     if (iOS7) {  
  36.         // 只有Xcode5才会编译这段代码  
  37. #ifdef __IPHONE_7_0  
  38.         titleW = [self.currentTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.width;  
  39. #else  
  40.         titleW = [self.currentTitle sizeWithFont:self.titleFont].width;  
  41. #endif  
  42.     } else {  
  43.         titleW = [self.currentTitle sizeWithFont:self.titleFont].width;  
  44.     }  
  45.     CGFloat titleH = contentRect.size.height;  
  46.     return CGRectMake(titleX, titleY, titleW, titleH);  
  47. }  
  48. - (CGRect)imageRectForContentRect:(CGRect)contentRect  
  49. {  
  50.     CGFloat imageW = 30;  
  51.     CGFloat imageX = contentRect.size.width - imageW;  
  52.     CGFloat imageY = 0;  
  53.     CGFloat imageH = contentRect.size.height;  
  54.     return CGRectMake(imageX, imageY, imageW, imageH);  
  55. }  
  56. @end  

在Button所在的控制器中,连线实现淡季事件

[objc]  view plain copy

  1. - (IBAction)titleClick:(UIButton *)sender {  
  2.     // 1.按钮旋转  
  3.     [UIView animateWithDuration:0.25 animations:^{  
  4.         sender.imageView.transform = CGAffineTransformMakeRotation(-M_PI);  
  5.     }];  
  6.     // 2.添加uiview  
  7.     UIView *temp  = [[UIView alloc] init];  
  8.     temp.frame = CGRectMake(10, 10, 100, 30);  
  9.     temp.backgroundColor = [UIColor redColor];  
  10.     [self.view addSubview:temp];  
  11. }  
【深入浅出IOS开发】彩票-重写按钮控件