Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button with Image and Text vertically aligned using autolayout constraints

I m very new to IOS development and AutoLayout . I am facing issues to align the Image and Text inside UIbutton using Storyboard. I had tried to achieve it with TitleEdgeinset and ImageEdge insets accordingly to place the Title ( text ) vertically centered below the Image. But the issue is I have 3 similar buttons which are Vertically stacked ( StackView) and the Text is dynamically set since we have localized strings ( includes Arabic rtl ) . The image and text moves according to the text length. Is there any ways that I can achieve to make all the buttons with image and text vertically alligned.Also, different screen resolutions are not currently working if using edge insets. Appreciate your help . Thanks in advance.

like image 659
user2695433 Avatar asked Jan 08 '16 17:01

user2695433


2 Answers

Few days ago, I solved similar problem,try this

 private func adjustImageAndTitleOffsetsForButton (button: UIButton) {

    let spacing: CGFloat = 6.0

    let imageSize = button.imageView!.frame.size

    button.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width, -(imageSize.height + spacing), 0)

    let titleSize = button.titleLabel!.frame.size

    button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0, 0, -titleSize.width)
}

call this method for each button, like

self.adjustImageAndTitleOffsetsForButton(yourButton)
like image 148
Ajay Kumar Avatar answered Sep 23 '22 03:09

Ajay Kumar


Combining Ajay's and Matej's answer:

UIButton with vertically aligned image and text

import Foundation
import UIKit
class VerticalButton: UIButton {
override func awakeFromNib() {
    super.awakeFromNib()
    self.contentHorizontalAlignment = .left
}

override func layoutSubviews() {
    super.layoutSubviews()
    centerButtonImageAndTitle()
}

private func centerButtonImageAndTitle() {
    let titleSize = self.titleLabel?.frame.size ?? .zero
    let imageSize = self.imageView?.frame.size  ?? .zero
    let spacing: CGFloat = 6.0
    self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing),left: 0, bottom: 0, right:  -titleSize.width)
    self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0)
 }
}
like image 23
abhimuralidharan Avatar answered Sep 25 '22 03:09

abhimuralidharan