Search code examples
swiftuiimageposition

Changing the UIImage position programmarically


I have a UITableView with sections. I added a UImage in each cell, but it is on the left side, how can I change it to make it go to the right side?

this is my code for each cell:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cells")
    cell?.textLabel?.text = data[indexPath.section].subType[indexPath.row]
    cell?.textLabel?.textAlignment = .right
    cell?.textLabel?.font = UIFont(name: "GESSTwoLight-Light", size: 15)
    cell!.isUserInteractionEnabled = false;
    cell!.imageView?.image = UIImage(named: "username.png")

    return cell!
}

This is my UITableView


Solution

  • you simply have to do the following in the tableView(_:cellForRowAt:) method:

    cell.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
    cell.textLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
    cell.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
    

    This will create the following

    Credits goes to liau-jian-jie for sharing this solution, which also can be applied to UIButtons.