美文网首页iOS Developer
iOS搜索热词实现

iOS搜索热词实现

作者: TooXu | 来源:发表于2017-04-21 17:22 被阅读562次

iOS搜索热词实现github链接

例图
需求中需要实现搜索页面展示搜索热词。
遇到的主要问题是:词汇如何进行换行,以及自身高度的适应。
///button 文字两边空隙 
CGFloat const btnEnhanceW = 24;
///button 左右之间间距
CGFloat const btnMargin = 15;
///button 上下间距
CGFloat const btnMarginTB = 10;
///button 高度
CGFloat const btnH = 22; `

遍历数据源添加button
通过计算行宽与容器宽度进行比较,来确定需不需要换行

CGFloat btnW = button.bounds.size.width + btnEnhanceW + btnMargin;
  tempSum += btnW;
 if (tempSum < self.bounds.size.width + btnMargin ) {
    [btnsArr addObject:button];
 }else{
    tempSum = btnW;
    btnsArr = [NSMutableArray array];
    [btnsArr addObject:button];
    [_rowsContainer addObject:btnsArr];
 }

button初始化完成后,开始布局。

 CGFloat btnY = 0;
 for (int index = 0;index < self.rowsContainer.count; index++) {
     NSArray<UIButton *> *btnsArr = self.rowsContainer[index];
     if (index == 0) {
         btnY = 15;
     }else {
         btnY = 15 + (btnH + btnMarginTB) * index;
     }
     for (int i = 0; i < btnsArr.count; i++) {
         UIButton *button = (UIButton *)[btnsArr objectAtIndex:i];
         [button sizeToFit];
         if (i == 0) {
             button.frame = CGRectMake(0, btnY, button.bounds.size.width + btnEnhanceW, btnH);
         }else {
             button.frame = CGRectMake(CGRectGetMaxX(btnsArr[i - 1].frame) + btnMargin, btnY, button.bounds.size.width + btnEnhanceW, btnH);
         }
        if (index == self.rowsContainer.count - 1 && i == btnsArr.count - 1)  {
         _selfHeight = CGRectGetMaxY(button.frame);
     }
   }
 }

- (void)setFrame:(CGRect)frame {
     [super setFrame:frame];
    _selfFrame = frame;
}

相关文章

网友评论

    本文标题:iOS搜索热词实现

    本文链接:https://www.haomeiwen.com/subject/vxodzttx.html