Skip to content

Instantly share code, notes, and snippets.

@bnickel
Created October 15, 2014 18:33
Show Gist options
  • Save bnickel/6a0ff1019db1e3a66237 to your computer and use it in GitHub Desktop.
Save bnickel/6a0ff1019db1e3a66237 to your computer and use it in GitHub Desktop.
A simple button where the left inset is adjusted to a fixed value, pinning the content to the right edge. Used in Stack Exchange.app to have a variable width empty button with an icon on the right side. Uses IBDesignable and IBInspectable so we never have to reference the button in code. :)
import UIKit
@IBDesignable
class SEUILeftInsetFromRightButton: UIButton {
@IBInspectable var leftInsetFromRight:CGFloat = 0 {
didSet {
updateContentEdgeInsetsWithWidth(CGRectGetWidth(bounds))
}
}
override var bounds:CGRect {
willSet(newValue) {
if CGRectGetWidth(newValue) != CGRectGetWidth(bounds) {
updateContentEdgeInsetsWithWidth(CGRectGetWidth(newValue))
}
}
}
override var frame:CGRect {
willSet(newValue) {
if CGRectGetWidth(newValue) != CGRectGetWidth(frame) {
updateContentEdgeInsetsWithWidth(CGRectGetWidth(newValue))
}
}
}
private func updateContentEdgeInsetsWithWidth(width:CGFloat) {
let leftInset = leftInsetFromRight > 0 ? width - leftInsetFromRight : 0
contentEdgeInsets = UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: 0)
}
override func intrinsicContentSize() -> CGSize {
var size = super.intrinsicContentSize()
size.width -= contentEdgeInsets.left
return size
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment