Я динамически добавляю UIImageView
(в виде миниатюры) и его NSLayoutConstraints
в моем UIView
который в ячейке таблицы. У меня есть две проблемы.UIImageView повторяет показ в других ячейках
После того, как изображение добавлено, если пользователь вставляет текст в эту таблицу, изображение показывается. Я имею в виду, вместо текстовой таблицы печатает еще одно изображение. Однако, если я остановлю и заново запустил приложение, на этот раз текст будет показан так, как должно быть. Тем не менее, если я напишу, появится текстовое изображение. Почему и что мне делать?
Я установил изображение и его ограничения, как это:
-(void)setThumbnail:(UIImageView)imageView { [self.messageView addSubview:imageView]; NSLayoutConstraint *leadingOfThumbnail = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.messageView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:8.f]; NSLayoutConstraint *trailingOfThumbnail = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.messageView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:-8.f]; NSLayoutConstraint *topOfThumbnail = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.messageView attribute:NSLayoutAttributeTop multiplier:1.0 constant:8.f]; NSLayoutConstraint *bottomOfThumbnail = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.messageView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-8.f]; [self.messageView addConstraint:leadingOfThumbnail]; [self.messageView addConstraint:trailingOfThumbnail]; [self.messageView addConstraint:topOfThumbnail]; [self.messageView addConstraint:bottomOfThumbnail]; [self.messageView setTranslatesAutoresizingMaskIntoConstraints:NO]; [self.messageView removeConstraints:[self.messageTextLabel constraints]]; }
И при загрузке, я получаю сообщение об ошибке ограничения. В нем написано:
2016-10-07 09:35:32.532 application[3733:2922397] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) (
"NSAutoresizingMaskLayoutConstraint:0x1281474d0 h=--& v=--& UIImageView:0x126d7e020.midY == + 100",
"NSAutoresizingMaskLayoutConstraint:0x128147520 h=--& v=--& V:[UIImageView:0x126d7e020(200)]",
"NSLayoutConstraint:0x126d6c880 V:|-(8)-[UIImageView:0x126d7e020] (Names: '|':UIView:0x1281480d0)")
Will attempt to recover by breaking constraint NSLayoutConstraint:0x126d6c880 V:|-(8)-[UIImageView:0x126d7e020] (Names: '|':UIView:0x1281480d0)
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
Я проверил, что установленные мной и ведущие и верхние ограничения приводят к этой ошибке. Они уже работают неправильно. Мое изображение 200 * 200, поэтому оно не требует ограничений по высоте и ширине. Я хочу только 8 pt ведущих, трейлинг, сверху, снизу из представления сообщений. В чем проблема?
спасибо.
Пояснение для первого вопроса: Таблица помещает UIImageView случайным образом, несколько ячеек - не так, как должно быть.
'[self.messageView addSubview: imageView];' Это преступник, потому что ячейка повторно используется. Так как вы, похоже, используете пользовательскую .m для своей ячейки, в 'prepareForReuse', удалите все subview из' self.messageView' там, где будет UIImageView. – Larme
@narsimelous: проблема с повторным использованием ячеек кэширования изображения, динамически добавленного в ячейку. Напишите некоторый метод resetThumbnail {}, чтобы проверить, присутствует ли изображение, а затем удалить его и сбросить ограничение ячейки в исходное состояние. перезагрузите его при каждом вызове prepareForReuse. – kaushal