Удалить SeparatorInset на iOS 8 UITableView для симулятора iPhone Xcode 6
Я обнаружил странное UITableView
пространство на UITableView
для iPhone 6 Simulator (iOS 8) на Xcode 6 GM. Я попытался установить SeparatorInset
как из раскадровки, так и из кода, но пробел остается там.
Следующий код работает на iOS 7, но не на iOS 8 (симулятор iPhone 6).
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
}
Я прикрепил скриншот ниже:
![iPhone 6 Simulator weird white space on tableview]()
Кстати, я использую AutoLayout. Я надеюсь, что кто-то может показать мне способ удалить странное пустое пространство в TableView
.
Ответы
Ответ 1
Спасибо студенту за то, что указали мне в правильном направлении с комментарием "Попробуйте это self.myTableView.layoutMargins = UIEdgeInsetsZero;" Эта строка кода будет работать только на iOS 8, поскольку layoutMargins доступен только с iOS 8. Если я запустил тот же код на iOS 7, он сработает.
@property(nonatomic) UIEdgeInsets layoutMargins
Description The default spacing to use when laying out content in the view.
Availability iOS (8.0 and later)
Declared In UIView.h
Reference UIView Class Reference
![enter image description here]()
Ниже приведен правильный ответ, чтобы решить это странное пустое пространство, установив tableview layoutMargins
и cell layoutMargins
как UIEdgeInsetsZero
, если он существует (для iOS 8). И это не сработает на iOS 7.
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[tableView setLayoutMargins:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
Смотрите снимок экрана ниже: -
![enter image description here]()
Ответ 2
Попробуйте создать класс класса UITableViewCell и добавьте этот getter
- (UIEdgeInsets)layoutMargins {
return UIEdgeInsetsZero;
}
в iOS7 это не будет называться cos, нет этого свойства в SDK и не вызовет какого-либо сбоя;
в iOS8 это будет вызываться каждый раз, когда вы используете ячейку
Это работает для меня
Ответ 3
Мое решение с тремя строками кода:
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)row{
//
// ... your code ...
//
if ([cell respondsToSelector:@selector(preservesSuperviewLayoutMargins)]){
cell.layoutMargins = UIEdgeInsetsZero;
cell.preservesSuperviewLayoutMargins = false;
}
return cell;
}
Ответ 4
IOS8 представляет новую концепцию с именем Конфигурирование полей содержимого, новое свойство с именем layoutMargins, также для ознакомления с деталями свойства, пожалуйста, обратитесь к Apple Doc. Тип layoutMargins - UIEdgeInsets, по умолчанию значение равно {8,8,8,8}. Чтобы удалить строку seperator TableView в IOS8, в дополнение к набору tableView.seperatorInset = UIEdgeInsetsZero
, вы также должны сделать следующее:
Сначала определите макрос
#define isIOS8SystemVersion (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
В методе UITableViewDelegate добавьте:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseId = @"cellReuseID" ;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
if(!cell){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseId];
if(isIOS8SystemVersion){
cell.layoutMargins = UIEdgeInsetsZero;
cell.preservesSuperviewLayoutMargins =NO ;
}
}
Выполнение этих действий приведет к удалению разделительной линии. Вы также можете сделать следующее:
UITableView *tableView = [[UITableView alloc] init];
if(isIOS8SystemVersion){
tableView.layoutMargins = UIEdgeInsetsZero ;
}
и в методе UITableViewDelegate добавьте:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseId = @"cellReuseID" ;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
if(!cell){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseId];
if(isIOS8SystemVersion){
cell.layoutMargins = UIEdgeInsetsZero;
}
}
Ответ 5
В моем случае в Xcode 6.2, помимо ответа на Q, я должен перейти в Main.storyboard > выбрать UITableViewCell > Attributes Inspector. Измените раскрывающийся список Separator с вкладками по умолчанию на Пользовательские вставки. Измените левую вставку с 15 на 0.
![enter image description here]()
Ответ 6
Обходной путь для iOS 7 и iOS 8
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.separatorInset = UIEdgeInsetsMake(0.0f, cell.frame.size.width, 0.0f, 0.0f);
}
Ответ 7
В iOS8 вам нужно установить Inset и на уровне Row и на уровне таблицы.
Уровень строки в cellForRowAtIndexPath:
if ([cell respondsToSelector:@selector(preservesSuperviewLayoutMargins)]){
cell.layoutMargins = UIEdgeInsetsZero;
cell.preservesSuperviewLayoutMargins = false;
}
Уровень таблицы в viewDidLoad:
[tableReference setSeparatorInset:UIEdgeInsetsZero];
После этого рекомендуется очистить ваш проект. В некоторых случаях я заметил, что эти изменения не были непосредственно введены в исполняемое приложение в симуляторе.
Ответ 8
для iOS 8
попробуйте установить cell.layoutMargins = UIEdgeInsetsZero;
в cellForRowAtIndexPath
метод
Ответ 9
Если вы хотите удалить белую строку, но сохраните вставку сепаратора, как только это, просто установите cell.backgroundColor в tableView backgroundColor. Просто настройка cell.contentView.backgroundColor не устраняет проблему.
Ответ 10
Я пробовал много способов, никто из них не работает, но этот работает для меня.
![WORK FOR ME]()
Ответ 11
Добавьте загрузочные изображения для iPhone 6 и Plus. Перед добавлением изображений телефон работает в режиме масштабирования, то есть более старые приложения масштабируются, чтобы соответствовать новым размерам экрана. Это может вызывать линии.
Новые изображения - Retina HD 5.5 (iPhone6Plus) 1242x2208 и Retina HD 4.7 (iPhone6) 750x1334.
Ответ 12
См. iOS 8 Вставка разделителя UITableView 0 не работает
В принципе, вам нужно установить как cell.layoutMargin, так и tableView layoutMargin. YMMV, но мне нужно было установить представление таблицы в layoutSubviews, прежде чем он сработает!
Ответ 13
Чтобы сделать вкладки сепаратора UITableView равными нулю для iOS7 и iOS8, вместо внесения изменений в код, внесите изменения в xib для UITableView, изменив View- > Mode- > Aspect Fill.
Ответ 14
У меня есть статический UITableView
и мне нужно сдвинуть границу разделителя ячейки на левый край.
Благодаря вышеприведенным ответам это было моим решением
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// needed to shift the margin a specific cell to the left edge
if indexPath.section == 3 && indexPath.row == 0 {
cell.layoutMargins = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
}
}
Ответ 15
Просто добавьте следующее:
tableView.separatorStyle = .none