標籤:object enter font add iphone5s 代碼 標籤 center header
前一陣時間,看過這樣一個demo,代碼不多,但是簡潔易懂。
轉自:
// 代碼地址: https://github.com/iphone5solo/PYSearch
// 代碼地址: http://www.code4app.com/thread-11175-1-1.html
/** 添加和布局標籤 */- (NSArray *)addAndLayoutTagsWithTagsContentView:(UIView *)contentView tagTexts:(NSArray<NSString *> *)tagTexts;{ // 清空標籤容器的子控制項 [contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; // 添加熱門搜尋標籤 NSMutableArray *tagsM = [NSMutableArray array]; for (int i = 0; i < tagTexts.count; i++) { UILabel *label = [self labelWithTitle:tagTexts[i]]; [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tagDidCLick:)]]; [contentView addSubview:label]; [tagsM addObject:label]; } // 計算位置 CGFloat currentX = 0; CGFloat currentY = 0; CGFloat countRow = 0; CGFloat countCol = 0; // 調整布局 for (UILabel *subView in tagsM) { // 當搜尋字數過多,寬度為contentView的寬度 if (subView.py_width > contentView.py_width) subView.py_width = contentView.py_width; if (currentX + subView.py_width + PYMargin * countRow > contentView.py_width) { // 得換行 subView.py_x = 0; subView.py_y = (currentY += subView.py_height) + PYMargin * ++countCol; currentX = subView.py_width; countRow = 1; } else { // 不換行 subView.py_x = (currentX += subView.py_width) - subView.py_width + PYMargin * countRow; subView.py_y = currentY + PYMargin * countCol; countRow ++; } } // 設定contentView高度 contentView.py_height = CGRectGetMaxY(contentView.subviews.lastObject.frame); // 設定頭部高度 self.baseSearchTableView.tableHeaderView.py_height = self.headerContentView.py_height = CGRectGetMaxY(contentView.frame) + PYMargin * 2; // 重新賦值, 注意:當作業系統為iOS 9.x系列的tableHeaderView高度設定失效,需要重新設定tableHeaderView [self.baseSearchTableView setTableHeaderView:self.baseSearchTableView.tableHeaderView]; return [tagsM copy];}
/** 添加標籤 */
- (UILabel *)labelWithTitle:(NSString *)title
{
UILabel *label = [[UILabel alloc] init];
label.userInteractionEnabled = YES;
label.font = [UIFont systemFontOfSize:12];
label.text = title;
label.textColor = [UIColor grayColor];
label.backgroundColor = [UIColor py_colorWithHexString:@"#fafafa"];
label.layer.cornerRadius = 3;
label.clipsToBounds = YES;
label.textAlignment = NSTextAlignmentCenter;
[label sizeToFit];
label.py_width += 20;
label.py_height += 14;
return label;
}
【轉】iOS,搜尋標籤布局