由几个视图组成的视图。可以将其视为一个 '不可滚动' 的水平集合视图。
使用 Cocoapods 添加 YZHorizontalItemsView。如果您还没有使用过 Cocoapods,可以 查看其页面
# Your pod file
pod 'YZHorizontalItemsView'
然后运行以下命令
pod update
首先,导入头文件。
#import <YZHorizontalItemsView/YZHorizontalItemsView.h>
您可以在您的代码中使用 initWithFrame: 创建 YZHorizontalItemsView,然后使用一个 Array 设置其 "itemsArray"。
@property (nonatomic, strong) YZHorizontalItemsView *itemsViewA;
...
self.itemsViewA =
[[YZHorizontalItemsView alloc] initWithFrame:CGRectMake(20, 100, 300, 100)];
NSMutableArray *itemsArrayA = [NSMutableArray array];
for (NSUInteger idx = 0; idx < 6; idx++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setText:[NSString stringWithFormat:@"%lu", (unsigned long)idx]];
[label setTextColor:[UIColor blackColor]];
[label setTextAlignment:NSTextAlignmentCenter];
[label setShadowColor:[UIColor colorWithWhite:0.5 alpha:0.5]];
[label setBackgroundColor:[UIColor colorWithHue:idx*0.1 saturation:1 brightness:1 alpha:1]];
[itemsArrayA addObject:label];
}
self.itemsViewA.itemsArray = [NSArray arrayWithArray:itemsArrayA];
[self.view addSubview:self.itemsViewA];
您也可以使用 storyboard 中的 YZHorizontalItemsView。设置 "itemsArray" 的更方便方法是使用 "itemAtIndex" 块。
@property (weak, nonatomic) IBOutlet YZHorizontalItemsView *itemsViewInStoryboardA;
...
[self.itemsViewInStoryboardA
setItemsArrayWithItemAtIndexBlock:^id(NSUInteger idx) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setText:[NSString stringWithFormat:@"%c", (char)idx + 'A']];
[label setTextAlignment:NSTextAlignmentCenter];
[label setBackgroundColor:[UIColor colorWithWhite:1-0.05*idx alpha:1]];
return label;
}
itemsCount:8
];
当用户点击一个项时,会调用 "itemTappedBlock"。
...
__weak typeof(self)weakSelf = self;
[self.itemsViewA setItemTappedBlock:^(NSUInteger idx, id item) {
UILabel *label = (UILabel*)item;
[weakSelf showAlertInfoForSelectedOption:label.text];
}];
...
- (void)showAlertInfoForSelectedOption:(NSString*)string{
NSString *message = [NSString stringWithFormat:@"The option is: '%@'.", string];
UIAlertController *alertController =
[UIAlertController alertControllerWithTitle:@"An option is selected." message:message preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
}]];
[self presentViewController:alertController animated:NO completion:nil];
}