UITableViewCell выравнивание изображения вправо, возможно? - PullRequest
5 голосов
/ 25 февраля 2012

при добавлении изображения в ячейку таблицы, по умолчанию оно идет влево:

cell.imageView.image = [UIImage imageNamed:[arrImages objectAtIndex:indexPath.row]];

как я могу изменить это, чтобы каждое изображение в UITableViewCell автоматически перемещалось вправо, а textLabel будет в 10 пикселей слева от изображения.

Большое спасибо!

Ответы [ 6 ]

10 голосов
/ 25 февраля 2012

Другой способ - создать пользовательскую ячейку и переопределить метод layoutSubviews.

@interface CustomCell : UITableViewCell

@end

@implementation CustomCell

- (void)layoutSubviews
{
   [super layoutSubviews];

   // grab bound for contentView
   CGRect contentViewBound = self.contentView.bounds;
   // grab the frame for the imageView
   CGRect imageViewFrame = self.imageView.frame;
   // change x position
   imageViewFrame.origin.x = contentViewBound.size.width - imageViewFrame.size.width;
   // assign the new frame
   self.imageView.frame = imageViewFrame;
}

@end

Помните, что в cellForRowAtIndexPath необходимо создавать и повторно использовать CustomCell, а не UITableViewCell.

Надеюсь, это поможет.

Редактировать

#import "CustomCell.h"

// other code here...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomCell";
    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    return cell;
}
5 голосов
/ 25 июня 2014

Найдите решение здесь код.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"foo.png"]];
cell.accessoryView = imageView;

Для справки.

UITableViewCell с изображением справа?

1 голос
/ 17 февраля 2018

в swift3 и swift4, мы можем использовать это:

cell.accessoryView = UIImageView (изображение: UIImage (по имени: "imageNmae")!)

1 голос
/ 22 сентября 2015

Здесь можно найти лучший ответ от @TomSwift https://stackoverflow.com/a/31616694/1884707

cell.contentView.transform = CGAffineTransformMakeScale(-1,1);
cell.imageView.transform = CGAffineTransformMakeScale(-1,1);
cell.textLabel.transform = CGAffineTransformMakeScale(-1,1);
cell.textLabel.textAlignment = NSTextAlignmentRight;

Применяя преобразование к ContentView, вы можете разместить imageView справа.

1 голос
/ 25 февраля 2012

попробуйте это:

cell.imageView.frame = CGRectMake(cell.frame.size.width - cell.imageView.frame.size.width, cell.imageView.frame.origin.y, cell.imageView.frame.size.width, cell.imageView.frame.size.height);
[cell.yourTexLabel sizeToFit];
cell.yourTexLabel.frame = CGRectMake(cell.imageView.origin.x - cell.yourTexLabel.frame.size.width - 10, cell.yourTexLabel.frame.origin.y, cell.yourTexLabel.frame.size.width, cell.yourTexLabel.frame.size.height);
0 голосов
/ 25 февраля 2012

Одним из решений является использование пользовательского UITableViewCell. Шаги:

  1. Создайте новый класс target-C, который является подклассом UITableViewCell, например LabeledImageTableViewCell. Объявите ivars и свойства для UILabel и UIImageView.
  2. В Интерфейсном Разработчике установите содержимое для UITableView в Динамические прототипы . Перетащите UIImageView и UILabel в ячейку табличного представления и расположите их. Установите класс ячейки на LabeledImageTableViewCell. Соедините выходы ячейки с UILabel & UIImageView объектами LabeledImageTableViewCell.
  3. В делегате для UITableView (обычно UITableViewController, иногда UIViewController) реализуйте методы источника данных , например:

    //#pragma mark - Table view data source
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return (NSInteger)[rowData count];
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"tvcLabeledImage";
        LabeledImageTableViewCell *cell = (LabeledImageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[LNCCorrelationInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        cell.myImage = [UIImage imageNamed:@"imageForThisRow.png"];
        cell.myLabel = "imageForThisRow";
        return cell;
    }
    

Кроме того, посмотрите видео Apple от WWDC 2011, Изменения, советы и хитрости UITableView и Представляем раскадровку Interface Builder (Требуется вход в систему: https://developer.apple.com/videos/wwdc/2011/.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...