Skip to content

Instantly share code, notes, and snippets.

@ohtwo
Created November 10, 2019 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohtwo/41d60e18ea0255ea1b8f87767fd2287d to your computer and use it in GitHub Desktop.
Save ohtwo/41d60e18ea0255ea1b8f87767fd2287d to your computer and use it in GitHub Desktop.
UIButton with vertiacal alignment image and title
import UIKit
class VerticalButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
titleLabel?.textAlignment = .center
}
override func titleRect(forContentRect content: CGRect) -> CGRect {
let title = super.titleRect(forContentRect: content)
let frame = CGRect(x: 0,
y: content.height - title.height,
width: content.width,
height: title.height)
return frame.offsetBy(dx: titleEdgeInsets.left - titleEdgeInsets.right,
dy: titleEdgeInsets.top - titleEdgeInsets.bottom)
}
override func imageRect(forContentRect content: CGRect) -> CGRect {
let image = super.imageRect(forContentRect: content)
let title = self.titleRect(forContentRect: content)
let frame = CGRect(x: content.width/2.0 - image.width/2.0,
y: title.minY/2.0 - image.height/2.0,
width: image.width,
height: image.height)
return frame.offsetBy(dx: imageEdgeInsets.left - imageEdgeInsets.right,
dy: imageEdgeInsets.top - imageEdgeInsets.bottom)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment