Ответ 1
У меня была такая же проблема и она была решена путем округления высоты:
newFrame.size.height = ceilf(expectedLabelSize.height);
У меня есть базовый UILabel, который я использую в UITableViewCell
. Я испытываю какое-то странное поведение, в некоторых ячейках (не все) UILabel получает серое верхнее поле, см. Рисунок ниже. И я не знаю, как это исправить.
Я создаю свой UILabel следующим образом:
if (self.postText == nil) {
CGRect postTextRect = CGRectMake(self.profileImage.frame.origin.x + self.profileImage.frame.size.width + 5, self.username.frame.origin.y + self.username.frame.size.height, frame.size.width - self.profileImage.frame.size.width - self.profileImage.frame.origin.y -10, self.frame.size.height - self.username.frame.size.height - self.username.frame.origin.y + 40);
self.postText = [[UILabel alloc] initWithFrame:postTextRect];
self.postText.backgroundColor = [UIColor whiteColor];
self.postText.textColor = [UIColor darkGrayColor];
self.postText.userInteractionEnabled = NO;
self.postText.numberOfLines = 0;
[self.containerView addSubview:self.postText];
}
Любые идеи о том, как исправить это?
Обновить
Мой cellForRowAtIndexPath
выглядит следующим образом:
- (id)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[...]
static NSString *postCellIdentifier = @"PostCell";
PostCell *cell = [tableView dequeueReusableCellWithIdentifier:postCellIdentifier];
if (cell == nil) {
cell = [[PostCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:postCellIdentifier];
}
[self configureCell:cell atIndexPath:indexPath forPost:cellPost];
return cell;
}
И соответствующий параметр configureCell
выглядит следующим образом:
- (void)configureCell:(PostCell *)cell atIndexPath:(NSIndexPath *)indexPath forPost:(Post *)post
{
[...]
cell.username.text = cellUser.username;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
CGSize maximumLabelSize = CGSizeMake(cell.postText.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [cell.postText.text sizeWithFont:cell.postText.font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect newFrame = cell.postText.frame;
newFrame.size.height = expectedLabelSize.height;
cell.postText.frame = newFrame;
CGRect containerRect = CGRectMake(5, 5, cell.containerView.frame.size.width, cell.postText.frame.size.height + cell.username.frame.origin.y + cell.username.frame.size.height + 10);
if (containerRect.size.height < 65) {
containerRect.size.height = 65;
}
cell.containerView.frame = containerRect;
[...]
}
У меня была такая же проблема и она была решена путем округления высоты:
newFrame.size.height = ceilf(expectedLabelSize.height);
Вышла та же проблема
Решено, назначив цвет и ширину границы для UILabel
nameLabel.layer.borderColor = [[UIColor whiteColor]CGColor];
nameLabel.layer.borderWidth = 2.0f;
Это ошибка IOS. Ошибка инициируется значением высоты поплавка метки. Таким образом, простой и не побочный эффект для решения этой проблемы - преобразование значения высоты поплавка в значение int:
(int)(label.frame.size.height)
попробуйте следующее:
cell.postText.layer.borderColor = self.Detail.backgroundColor.CGColor;
cell.postText.layer.borderWidth = 1;
Странные серые контуры обусловлены тем, что размер фона и размер метки не являются точными.
Это можно решить отлично:
[myLabel sizeToFit]
Вместо этого решил использовать UITextView
.
Проблема возникает при изменении кадра UILabel.
Измените этот код:
CGSize maximumLabelSize = CGSizeMake(cell.postText.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [cell.postText.text sizeWithFont:cell.postText.font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect newFrame = cell.postText.frame;
newFrame.size.height = expectedLabelSize.height;
cell.postText.frame = newFrame;
чтобы...
[cell.postText sizeToFit];
Удалил границу. Но содержимое отображалось не так, как я этого хотел, поэтому я перешел на UITextView
Настоящая причина заключается в том, что высота или ширина рамки не являются целыми или меняют цвет фона вашего приложения, чтобы очистить цвет.
把 рама 的 ширина 或者 высота 修改 为 整数, 或者 设置 背景 色 为 прозрачный цвет 即可.
Кажется, что проблема возникает, если вы изменяете свойство фрейма метки, задаете ширину или высоту с помощью значения float.
Это решение работает для меня, устанавливая backgroundColor метки на Clear.
Objective-C:
[label setBackgroundColor:[UIColor clearColor]];
скор:
label.setBackgroundColor = UIColor.clearColor()