Search code examples
iosswiftuiimageviewnslayoutconstraint

UIImageView Alignment


I have a UIImageView in a tableviewcell and have the content mode set to scaleAspectFill:

let imageSize = CGSize(width: 70, height: 70)
MenuImage.contentMode = .scaleAspectFill

if(self.reuseIdentifier == "cell1") {
    MenuImage.image = UIImage.imageWithIonicon(.Map, color: UIColor.white, iconSize: 70, imageSize: imageSize)
}
else if (self.reuseIdentifier == "cell2") {
    MenuImage.image = UIImage.imageWithIonicon(.iOSPerson, color: UIColor.white, iconSize: 70, imageSize: imageSize)

}
else if (self.reuseIdentifier == "cell3") {
    MenuImage.image = UIImage.imageWithIonicon(.iOSHelp, color: UIColor.white, iconSize: 70, imageSize: imageSize)
}

Although this fits the image nicely to the cell, the image appears to align to the bottom. Is there a way to get it to centre vertically within the UIImageView (the brown background is just so I can check the size of the image view)

enter image description here


Solution

  • According to This in order to fix vertical alignment, in your "ionicons.swift" file you need to change this line:

    attString.drawInRect(CGRect(x: (imageSize.width / 2) - boundingRect.size.width / 2, y: (imageSize.height / 2) - boundingRect.size.height / 2, width: imageSize.width, height: imageSize.height))
    

    to

    attString.drawInRect(CGRect(x: (imageSize.width / 2) - (boundingRect.size.width / 2), y: (imageSize.height / 2) - (iconSize / 2), width: imageSize.width, height: imageSize.height))
    

    *Swift 3.0 version, replace this:

    attString.draw(in: CGRect(x: (imageSize.width / 2) - boundingRect.size.width / 2, y: (imageSize.height / 2) - boundingRect.size.height / 2, width: imageSize.width, height: imageSize.height))
    

    with

    attString.draw(in: CGRect(x: (imageSize.width / 2) - (boundingRect.size.width / 2), y: (imageSize.height / 2) - (iconSize / 2), width: imageSize.width, height: imageSize.height))