我有一个UIScrollView
我有3 UILabel
和3 UIButton
。我使用以下代码添加我的标签,但它保持顶部&标签内的下边距。
float height = 0.0f;
for (int i=0; i < answer_set.count; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20,height ,280,10 )];
[label setText: [self.answer_set objectAtIndex:i]];
[label setTextAlignment:NSTextAlignmentLeft];
[label setBackgroundColor:[UIColor redColor]];
label.textColor = [UIColor colorWithRed:0.2941f green:0.4666f blue:0.9549f alpha:1.0f];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
[label sizeToFit];
label.userInteractionEnabled = YES;
label.font = [UIFont fontWithName:@"Arial" size:14.0f] ;
[self.percentage_ans_view addSubview:label];
height += label.frame.size.height;
}
如果单行文本正常工作。 我该怎么做才能删除标签内部的这些顶部/底部间距。 ???
答案 0 :(得分:1)
首先你应该根据文字
获得标签高度 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20,height ,280,10 )];
[label setText: [self.answer_set objectAtIndex:i]];
[label setTextAlignment:NSTextAlignmentLeft];
[label setBackgroundColor:[UIColor redColor]];
label.textColor = [UIColor colorWithRed:0.2941f green:0.4666f blue:0.9549f alpha:1.0f];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.userInteractionEnabled = YES;
label.font = [UIFont fontWithName:@"Arial" size:14.0f] ;
[self.percentage_ans_view addSubview:label];
// get height base on label text and size
CGFloat height=[self getStringHeightforLabel:label];
//set fram after getting height
label.frame=CGRectMake(20,height,280,height);
[label sizeToFit];
//调用此方法获取身高
答案 1 :(得分:0)
我不确定我是否理解你的问题,但如果我这样做,你可以使用:
label.contentInset = UIEdgeInsetsMake(top, right, bittom, left);
设置标签内的间距
答案 2 :(得分:0)
你需要放置
[label sizeToFit];
恰好在addSubview之前。并且,在字体更改后,您有问题
label.font = [UIFont fontWithName:@"Arial" size:14.0f] ;
所以,您的代码必须如下所示:
float height = 0.0f;
for (int i=0; i < answer_set.count; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20,height ,280,10 )];
[label setText: [self.answer_set objectAtIndex:i]];
[label setTextAlignment:NSTextAlignmentLeft];
[label setBackgroundColor:[UIColor redColor]];
label.textColor = [UIColor colorWithRed:0.2941f green:0.4666f blue:0.9549f alpha:1.0f];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
// [label sizeToFit]; // NOT HERE
label.userInteractionEnabled = YES;
label.font = [UIFont fontWithName:@"Arial" size:14.0f] ;
[label sizeToFit]; // BUT HERE
[self.percentage_ans_view addSubview:label];
height += label.frame.size.height;
}