Last active
August 29, 2015 14:25
-
-
Save aral/300a0588563d4f52a950 to your computer and use it in GitHub Desktop.
Example of allowing free text entry of significant tokens in Interface Builder (for an @IBDesignable view) using a bitmask.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Unfortunately, this has to be a string right now as IBInspectable enums are not supported at the moment. | |
@IBInspectable var alignmentToParentName:String = "top right" | |
{ | |
didSet | |
{ | |
var name = (alignmentToParentName.lowercaseString as NSString) | |
let top = 0b00, bottom = 0b10, right = 0b00, left = 0b01 | |
var bitmask = 0b0 | |
// The default, even if garbage is entered in Interface Builder, is top right. | |
bitmask |= name.containsString("bottom") ? bottom : top | |
bitmask |= name.containsString("left") ? left : right | |
alignmentToParent = alignments[bitmask] | |
println("Alignment to parent is \(alignmentNames[bitmask]).") | |
} | |
} | |
enum Alignment { case topRight; case topLeft; case bottomRight; case bottomLeft; } | |
let alignments = [Alignment.topRight, Alignment.topLeft, Alignment.bottomRight, Alignment.bottomLeft] | |
let alignmentNames = ["top right", "top left", "bottom right", "bottom left"] |
Note: updated so that the default values are zeros and non-default values are ones (as per https://twitter.com/Bob_at_BH/status/622380717784367105 by Bob Koon). Also altered the order so that they match the language order in which we talk about the problem domain — in this case, the alignment of an unread count badge to its parent view: top-right, top-left, bottom-right, bottom-left.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So, basically, this would work regardless of whether you entered bottomLeft, bottom left, bottom-left, etc. in Interface Builder’s Attribute Inspector.
(Note: this was the first iteration for a feature. This parameter is actually unnecessary as the placement of the item in design view — relative to parent — should automatically determine alignment.)