ios 使UIToolbar项目均匀分布在工具栏上

nbnkbykc  于 2023-03-09  发布在  iOS
关注(0)|答案(1)|浏览(120)

这是我代码

UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 200, UIScreen.mainScreen.bounds.size.width, 44)];
self.toolbar = boolbar;
[self.view addSubview:toolbar];

NSMutableArray *arrayM = [NSMutableArray array];
NSArray *titles = @[@"title0", @"title1", @"title2", @"title3"];
for (int i = 0; i < titles.count; i++) {
    [arrayM addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace] target:nil action:nil];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0];
    [button setTitle:titles[i] forState:UIControlStateNormal];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    [arrayM addObject:item];
}
[arrayM addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace] target:nil action:nil];
toolbar.items = arrayM;

结果如下图screenshot所示
按钮的可点击范围太小,我不想给按钮设置固定大小,因为按钮标题会不一样。我想让每个按钮在工具栏上均匀分布,但我找不到合适的方法
我尝试使用系统提供的所有项目,但没有任何工作
all UIBarButtonSystemItem

fdx2calv

fdx2calv1#

iOS没有提供均匀分布UIToolbar项目的方法,但你可以通过一些技巧来解决这个问题。这是通过一个继承自UIToolbar的自定义类来实现的,如下所示:

@interface MYToolbar : UIToolbar

@end

@implementation MYToolbar
- (void)setItemsDistributionFillEqually:(UIView *)view {
    [view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[UIStackView class]]) {
            [(UIStackView *)obj setDistribution:UIStackViewDistributionFillEqually];
            *stop = YES;
        }
        [self setItemsDistributionFillEqually:obj];
    }];
}
- (void)layoutSubviews {
    [super layoutSubviews];
    [self setItemsDistributionFillEqually:self];
}
@end

相关问题