Last active
August 9, 2021 12:11
-
-
Save Isuru-Nanayakkara/496d5713e61125bddcf5 to your computer and use it in GitHub Desktop.
Add a border to a UIButton. Original code - http://stackoverflow.com/a/21881788/1077789
@elsurudo UIButtonBorderSide enum causes the problem - it's not bridgable to ObjC, so any methods which use it are also not bridgable. Only enums which have Int/UInt/etc as raw value can be bridged to ObjC.
Here, I modified this so you can add borders to multiple sides (or a single one) in one call. I don't know if it's possible to send pull requests or not for gists, so I'm just adding this as a comment.
https://gist.github.com/BrettRToomey/728c6f68ffbae47aa0b1638229e7367e
Here is the code for the Obj-C fellows
- (void)addBorderForSide:(UIButtonBorderSide)side color:(UIColor *)color width:(CGFloat)width{
CALayer *border = [CALayer layer];
border.backgroundColor = [color CGColor];
switch (side) {
case Top:
border.frame = CGRectMake(0, 0, self.frame.size.width, width);
break;
case Bottom:
border.frame = CGRectMake(0, self.frame.size.height - width, self.frame.size.width, width);
break;
case Left:
border.frame = CGRectMake(0, 0, width, self.frame.size.height);
break;
case Right:
border.frame = CGRectMake(self.frame.size.width - width, 0, width, self.frame.size.height);
break;
default:
break;
}
[self.layer addSublayer:border];
}
see my answer here: www.stackoverflow.com/a/40222533/2594699
Swift 4 + we can add this extension to UIView so its available across more elements.
public enum UIButtonBorderSide {
case top, bottom, left, right
}
extension UIView {
public func addBorder(side: UIButtonBorderSide, color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
switch side {
case .top:
border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: width)
case .bottom:
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
case .left:
border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
case .right:
border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
}
self.layer.addSublayer(border)
}
}
lmL
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm, for some reason I can't seem to call this method from ObjC code. I have the Swift bridging header imported, and I've even made the extension
public
. Any ideas?