ButtonGroupView.m 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // ButtonGroupView.m
  3. // ChinaCityList
  4. //
  5. // Created by zjq on 15/10/27.
  6. // Copyright © 2015年 zhengjq. All rights reserved.
  7. //
  8. #import "ButtonGroupView.h"
  9. #import "CityItem.h"
  10. #define isWidthOddNumber (int)self.frame.size.width % self.columns != 0
  11. #define kGridLineHeight 1
  12. #define kItmeSpacing 15
  13. //#define ContentViewWidth
  14. @implementation ButtonGroupView
  15. - (NSMutableArray *)buttons {
  16. if (_buttons == nil) {
  17. _buttons = [NSMutableArray array];
  18. }
  19. return _buttons;
  20. }
  21. - (void)layoutSubviews {
  22. [super layoutSubviews];
  23. CGFloat width = self.frame.size.width;
  24. long i = (_columns+1)*kItmeSpacing;
  25. CGFloat a = width-i;
  26. CGFloat buttonW = a / _columns;
  27. if (isWidthOddNumber) { //iphone6或iphone6+
  28. buttonW = (int)round(buttonW);
  29. }
  30. long rowNum = _items.count/_columns + (_items.count%_columns==0?0:1);
  31. CGFloat buttonH = (self.frame.size.height-rowNum*kItmeSpacing) / ((self.items.count - 1) / self.columns + 1);
  32. for (int index = 0; index < self.items.count; index++) {
  33. if (isWidthOddNumber) {
  34. if ((index + 1) * self.columns == 0) {
  35. buttonW = buttonW - 1;
  36. }
  37. }
  38. // i这个位置对应的列数
  39. int col = index % self.columns;
  40. // i这个位置对应的行数
  41. int row = index / self.columns;
  42. CGFloat buttonX = col * (buttonW+kItmeSpacing)+kItmeSpacing;
  43. CGFloat buttonY = row * (buttonH+kItmeSpacing);
  44. [self.buttons[index] setFrame:CGRectMake(buttonX, buttonY, buttonW, buttonH)];
  45. }
  46. }
  47. - (void)setItems:(NSArray *)items {
  48. _items = items;
  49. for (CityButton *cityButton in self.subviews) {
  50. [cityButton removeFromSuperview];
  51. }
  52. [self.buttons removeAllObjects];
  53. for (int index = 0; index < self.items.count; index++) {
  54. CityButton *cityButton = [[CityButton alloc] init];
  55. cityButton.tag = index;
  56. cityButton.index = index;
  57. cityButton.cityItem = self.items[index];
  58. [cityButton addTarget:self action:@selector(itemclick:) forControlEvents:UIControlEventTouchUpInside];
  59. [self addSubview:cityButton];
  60. [self.buttons addObject:cityButton];
  61. }
  62. }
  63. - (void)itemclick:(CityButton *)cityButton {
  64. if ([self.delegate respondsToSelector:@selector(ButtonGroupView:didClickedItem:)]) {
  65. [self.delegate ButtonGroupView:self didClickedItem:cityButton];
  66. }
  67. }
  68. @end