Подтвердить что ты не робот

Как изменить размер cell.imageView в TableView и применить tintColor в Swift

У меня есть tableView с ячейкой, созданной в cellForRowAtIndexPath, и добавьте некоторый фиктивный текст:

cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
            reuseIdentifier: "cell")
cell.textLabel?.text = "Test Title"
cell.detailTextLabel?.text = "Test detail label"

Затем я добавляю тестовое изображение в ячейку imageView:

var image = UIImage(named: "cd.png")
cell.imageView!.image = image

Результат:

введите описание изображения здесь

Чтобы настроить цвет, я использую следующий код:

cell.imageView?.tintColor = UIColor.redColor()

Результат:

Изображение, настроенное с учетом цвета

Изображение слишком велико в ячейке, поэтому я настраиваю размер, используя следующий код:

var itemSize:CGSize = CGSizeMake(20, 20)
UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.mainScreen().scale)
var imageRect : CGRect = CGRectMake(0, 0, itemSize.width, itemSize.height)
cell.imageView!.image?.drawInRect(imageRect)
cell.imageView!.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Во время изменения размера изображения tintColor теряется:

введите описание изображения здесь

Любые идеи, пожалуйста?

4b9b3361

Ответ 1

Вы можете сделать это по-другому:

1) Создайте собственную ячейку со своим собственным размером UIImageView и двумя отдельными ярлыками

2) Добавьте UIImageView в качестве Subview ячейки

var cellImg : UIImageView = UIImageView(frame: CGRectMake(5, 5, 50, 50))
cellImg.image = UIImage(named: "yourimage.png")
cell.addSubview(cellImg)

Ответ 2

Решение Без пользовательской ячейки

func imageWithImage(image:UIImage,scaledToSize newSize:CGSize)->UIImage{

    UIGraphicsBeginImageContext( newSize )
    image.drawInRect(CGRect(x: 0,y: 0,width: newSize.width,height: newSize.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage.imageWithRenderingMode(.AlwaysTemplate)
  }




override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell

    cell.imageView?.tintColor = UIColor.greenColor()
    cell.imageView?.image = imageWithImage(UIImage(named: "imageName")!, scaledToSize: CGSize(width: 20, height: 20))

    // Configure the cell...

    return cell
  }

Ответ 3

Для Swift 3

func imageWithImage(image:UIImage,scaledToSize newSize:CGSize)->UIImage{

        UIGraphicsBeginImageContext( newSize )
        image.draw(in: CGRect(x: 0,y: 0,width: newSize.width,height: newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!.withRenderingMode(.alwaysTemplate)
    }

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell

    cell.imageView?.tintColor = UIColor.greenColor()
    cell.imageView?.image = imageWithImage(image: UIImage(named: "imageName")!,scaledToSize: CGSize(width: 20, height: 20))

    // Configure the cell...

    return cell
  }

Ответ 4

Для OBJECTIVE C без Custom tableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

 {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"abc" forIndexPath:indexPath];

    // Configure the cell...

    if (cell==nil) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"abc"];

    }


    cell.textLabel.text = [menuItemsArray objectAtIndex:indexPath.row];

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


    CGSize  itemSize = CGSizeMake(20, 20);

    UIGraphicsBeginImageContextWithOptions(itemSize, false, self.view.contentScaleFactor);

    CGRect  imageRect = CGRectMake(0, 0, itemSize.width, itemSize.height);

    [cell.imageView.image drawInRect:imageRect];

    cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();






    return cell; }