Arun Kumar
Arun Kumar

Reputation: 491

iOS - Constraint to UIImage with centrally aligned UILabel's text

I have UITableViewCell that has a UIlabel aligned center I'm setting image in default imageView property of the UITableViewCell but since text is aligned center there is a gap between text and the image.

I want image then little space then text all center to UITableViewCell I have tried following code,

    cell.imageView?.image = image
    cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
    cell.imageView?.centerYAnchor.constraint(equalTo: label.centerYAnchor).isActive = true
    let rect: CGRect = label.textRect(forBounds: label.bounds, limitedToNumberOfLines: 1)
    cell.imageView?.leadingAnchor.constraint(equalTo: label.leadingAnchor, constant: rect.origin.x - padding).isActive = true

That works for me but when I switch device from iPhone 11 Max Pro to iPhone 8 image overlaps the text because label.textRect always brings the same text irrespective of screen size

I have also tried using range of the first later and using it's rect but same problem of not being changed per screen size.

Can this be achieved without putting custom UIImageView in UITableViewCell?

Upvotes: 1

Views: 225

Answers (1)

rs7
rs7

Reputation: 1630

You could use a stackView that you center inside your cell and add your imageView and your label as arranged subViews. Note that you would need to create a custom cell.

  1. Create your stackView:

    let stackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.alignment = .center
        stackView.distribution = .fill
        stackView.spacing = 10 // You can set the spacing accordingly
        return stackView
    }()
    
  2. Layout as follows:

    contentView.addSubview(stackView)
    
    // Swap these two lines if instead you want label then image
    stackView.addArrangedSubview(image)
    stackView.addArrangedSubview(label)
    
    // StackView
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true
    stackView.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor).isActive = true
    

Upvotes: 1

Related Questions