標籤:
在開發工作中遇到了一個對我來說非常難得問題,搞了兩天呀,都虛脫了,終於騙到大神給的demo做了出來效果是這樣
首先背景同事傳一個字串。。拒絕傳數組,那麼我們就要學會分割!
NSString *tagStr = [dictionary valueForKey:@"tags"];
NSArray *statusArray = [tagStr componentsSeparatedByString:@","];
這個就是把字串按照符號分割數組的方法,接下來我們就可以根據內容動態產生標籤了;
這是用到的宏:
#define FONT_SIZE 13.0f
#define HORIZONTAL_PADDING 7.0f
#define VERTICAL_PADDING 3.0f
#define CORNER_RADIUS 10.0f
#define LABEL_MARGIN 5.0f
#define BOTTOM_MARGIN 5.0f
#define BACKGROUND_COLOR UIColorFromRGB(0x04, 0x9f, 0xf1)
//[UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1.00]
#define TEXT_COLOR [UIColor whiteColor]
#define TEXT_SHADOW_COLOR [UIColor whiteColor]
#define TEXT_SHADOW_OFFSET CGSizeMake(0.0f, 1.0f)
#define BORDER_COLOR [UIColor lightGrayColor].CGColor
#define BORDER_WIDTH 1.0f
這是代碼:
if (tagStr.length > 0)//判斷一下有值才產生
{
float totalHeight = 0;//
CGRect previousFrame = CGRectZero;
BOOL gotPreviousFrame = NO;//檢查是否有前一個標籤
for (NSString *text in statusArray)
{
CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:CGSizeMake(self.frame.size.width, 1500) lineBreakMode:UILineBreakModeWordWrap];//動態擷取字串長度
textSize.width += HORIZONTAL_PADDING*2;
textSize.height += VERTICAL_PADDING*2;
UILabel *label = nil;
if (!gotPreviousFrame)
{
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, textSize.width, textSize.height)];
totalHeight = textSize.height;
}
else
{
CGRect newRect = CGRectZero;
if (previousFrame.origin.x + previousFrame.size.width + textSize.width + LABEL_MARGIN > self.frame.size.width) {
newRect.origin = CGPointMake(0, previousFrame.origin.y + textSize.height + BOTTOM_MARGIN);
totalHeight += textSize.height + BOTTOM_MARGIN;
}
else
{
newRect.origin = CGPointMake(previousFrame.origin.x + previousFrame.size.width + LABEL_MARGIN, previousFrame.origin.y);
}
newRect.size = textSize;
label = [[UILabel alloc] initWithFrame:newRect];
}
previousFrame = label.frame;
gotPreviousFrame = YES;
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
if (!lblBackgroundColor)
{
[label setBackgroundColor:BACKGROUND_COLOR];
} else
{
[label setBackgroundColor:lblBackgroundColor];
}
[label setTextColor:TEXT_COLOR];
[label setText:text];
[label setTextAlignment:UITextAlignmentCenter];
// [label setShadowColor:TEXT_SHADOW_COLOR];
// [label setShadowOffset:TEXT_SHADOW_OFFSET];
[label.layer setMasksToBounds:YES];
[label.layer setCornerRadius:CORNER_RADIUS];
[label.layer setBorderColor:BORDER_COLOR];
[label.layer setBorderWidth: BORDER_WIDTH];
[_CorpTagView addSubview:label];
}
sizeFit = CGSizeMake(self.frame.size.width, totalHeight + 1.0f);//這個我一直不知道什麼作用,抄來的O(∩_∩)O哈哈~
}
ios開發筆記根據傳入字串的長度動態產生label,並按照螢幕寬度排列