iOS shadow view in interface builder - ios

I'm trying to add shadows to some views via interface builder. I can't seem to get shadows to work on my views. All the resources I look at point to this same code so I'm not sure what I'm doing wrong.
Interface Builder
Interface Builder Extension code
import Foundation
import UIKit
extension UIView {
//cut irrelevant code for SO Question
#IBInspectable
var masksToBounds: Bool {
get {
return layer.masksToBounds
}
set {
layer.masksToBounds = newValue
}
}
// Shadow handling
#IBInspectable
var shadowColor: UIColor? {
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.shadowColor = color.cgColor
} else {
layer.shadowColor = nil
}
}
}
#IBInspectable
var shadowOpacity: Float {
get {
return layer.opacity
}
set {
layer.opacity = newValue
}
}
#IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
#IBInspectable
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
}
Views layout
This is the result

Your shadowOpacity property is accessing the wrong layer property. It's accessing layer.opacity when it should be layer.shadowOpacity. Also, your shadowRadius is way too large and should probably be around 5 (depending on what you're going for, of course), not 500.

I guess it's your custom search bar to which you're adding shadow. The reason its not visible I guess is because your both view in controller and storyboard of same size. Try to make the storyboard view have a container view in it with some padding along to the storyboard view and add that shadow to that container view. This might show some results.

Related

Increasing the corner radius of UITextField removes its shadow

I have a UITextField with custom code to control the corner radius and the placeholder color and another different properties. Also, I have a Protocol with Extension to drop shadow from any UI element.
The problem is: whenever I increase the corner radius of the text field, I lose the shadow. As long as the corner radius is 0, I still have a shadow.
And this shows at the debugger when I increase the cornerRadius and lose the shadow:
setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key height
Here is my Protocol I implemented to drop shadow:
import UIKit
protocol DropShadow {}
extension DropShadow where Self: UIView {
func addDropShadow() {
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.7
layer.shadowOffset = CGSize(width: 0, height: 4)
layer.shadowRadius = 3
}
}
And here is my custom class for the UITextField:
import UIKit
#IBDesignable
class FancyTextField: UITextField, DropShadow {
#IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
#IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
#IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
#IBInspectable var bgColor: UIColor? {
didSet {
backgroundColor = bgColor
}
}
#IBInspectable var placeHolderColor: UIColor? {
didSet {
let rawString = attributedPlaceholder?.string != nil ? attributedPlaceholder!.string : ""
let str = NSAttributedString(string: rawString, attributes: [NSForegroundColorAttributeName: placeHolderColor!])
attributedPlaceholder = str
}
}
}
When you add a corner radius to a UIView you have to set the clipsToBounds or masksToBounds to be true. That doesn't allow the shadow to be created as the shadow is created outside the bounds.
As a solution for this problem, you will have to create a superView to the UIView that has the clipped corners, and add a shadow to this superView (Make sure to set the superview to clear color)

Circular ImageView Swift

I have tried every answer variation I have found and all give me the same result. A weird almost diamond shaped image view. I was using this:
imageView.layer.cornerRadius = imageView.frame.width/2
imageView.clipsToBounds = true
This worked with a previous project I was working on but now when I try it I get the weird diamond.
Here is the solution how to create UIImageView Circular. This Approach is new
Create a new Designable.swift file in your project.
Copy the following code in your Designable.swift file.
import UIKit
#IBDesignable class DesignableImageView: UIImageView { }
#IBDesignable class DesignableButton:UIButton { }
#IBDesignable class DesignableTextField:UITextField { }
extension UIView {
#IBInspectable
var borderWidth :CGFloat {
get {
return layer.borderWidth
}
set(newBorderWidth){
layer.borderWidth = newBorderWidth
}
}
#IBInspectable
var borderColor: UIColor? {
get{
return layer.borderColor != nil ? UIColor(CGColor: layer.borderColor!) :nil
}
set {
layer.borderColor = newValue?.CGColor
}
}
#IBInspectable
var cornerRadius :CGFloat {
get {
return layer.cornerRadius
}
set{
layer.cornerRadius = newValue
layer.masksToBounds = newValue != 0
}
}
#IBInspectable
var makeCircular:Bool? {
get{
return nil
}
set {
if let makeCircular = newValue where makeCircular {
cornerRadius = min(bounds.width, bounds.height) / 2.0
}
}
}
}
Now after this select your ImageView on StoryBoard and Select Identity Inspector from Utilities Panel.
In Custom Class section select the custom class from the drop-down menu naming DesignableImageView and hit return. You will see the designable update after hitting return.
Now go to attribute inspector in utility panel and you can add the desired Corner Radius for the image to be circular.
P.S. If your image is rectangle this will try to make it square and then best possible circle.
Attached images for reference.
Try changing the view mode for the uiimageview. It might have been set to Aspect fit making it to look like a diamond.
Or you can create a circular uiimage using the code below,
imageLayer.contents = yourImage.CGImage
let mask = CAShapeLayer()
let dx = lineWidth + 1.0
let path = UIBezierPath(ovalInRect: CGRectInset(self.bounds, dx, dx))
mask.fillColor = UIColor.blackColor().CGColor
mask.path = path.CGPath
mask.frame = self.bounds
layer.addSublayer(mask)
imageLayer = CAShapeLayer()
imageLayer.frame = self.bounds
imageLayer.mask = mask
imageLayer.contentsGravity = kCAGravityResizeAspectFill
layer.addSublayer(imageLayer)
If you want to create with new image it may be like this
let img = UIImage(named: "logo.png")
UIGraphicsBeginImageContextWithOptions(imgView.bounds.size, false, 0.0);
// Add a clip before drawing anything, in the shape of an rounded rect
UIBezierPath(roundedRect: imgView.bounds, cornerRadius:imgView.bounds.size.width/2).addClip()
img!.drawInRect(imgView.bounds)
imgView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
Ref & If you want to make extension for it : https://stackoverflow.com/a/25459500/4557505
You can find more information in the above link for other alternative solutions
Your image view should be a square in order for this to work.
if you are trying this code in viewDidLoad(), please try it in viewDidLayoutSubviews()
viewDidLayoutSubviews() {
imageView.layer.cornerRadius = imageView.frame.size.width/2
imageView.layer.masksToBounds = true
}
extension UIImageView {
public func maskCircle(inputImage: UIImage) {
self.contentMode = UIViewContentMode.scaleAspectFill
self.layer.cornerRadius = self.frame.height / 2
self.layer.masksToBounds = false
self.clipsToBounds = true
self.image = inputImage
}
}
Usage example of the above extension:
let yourImage:UIImage = UIImage(named: "avatar")!
yourImageView.maskCircle(yourImage)

Add border to all labels in a view

In my app I have a custom view containerView in this view there are more than 20 labels and I want to apply a border style to all of them.
Is there a way to avoid to add the border to each of them avoiding to have a long list?
Something similar to:
for each label in containerView {
labels.layer.borderColor = UIColor.greenColor.CGColor
}
create a subclass like this:
#IBDesignable
class BorderedLabel: UILabel {
#IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
#IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
}
then change your label's custom class in interface builder, set the borderColor / borderWidth properties you like and see the results live in interface builder!
You need to set borderWidth.
for subview in self.view.containerView.subviews as! [UIView] {
if let label = subview as? UILabel {
label.layer.borderColor = UIColor.greenColor().CGColor
label.layer.borderWidth = 1
}
}
Swift 4
label.layer.borderColor = UIColor.green.cgColor
You can use this:
for view in self.view.containerView.subviews as! [UIView] {
if let label = view as? UITextField {
label.layer.borderColor = UIColor.blueColor().CGColor;
label.layer.borderWidth = 1;
}
}
}
My solution is:
for imageViews in self.containerView.subviews as! [UIImageView] {
imageViews.layer.borderColor = UIColor.greenColor().CGColor
imageViews.layer.borderWidth = 1
}

Set a border for UIButton in Storyboard

I can't get a border onto my buttons in Xcode 5 without setting them directly in the code. Is it possible that there's no way to do this on the storyboard without making a custom background image?
You can use key path.
For example the corner radius (layer.cornerRadius) as describe on the image.
You will not be able to see the effects on storyboard, cause this parameters are evaluated at runtime. Now you can use a swift category in UIView (code bellow the picture) in with #IBInspectable to show the result at the storyboard (If you are using the category, use only cornerRadius and not layer.cornerRadius as a key path.
extension UIView {
#IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
}
Here is category from Peter DeWeese answer that allow use keypath layer.borderUIColor to set the border color.
CALayer+XibConfiguration.h:
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
#interface CALayer(XibConfiguration)
// This assigns a CGColor to borderColor.
#property(nonatomic, assign) UIColor* borderUIColor;
#end
CALayer+XibConfiguration.m:
#import "CALayer+XibConfiguration.h"
#implementation CALayer(XibConfiguration)
-(void)setBorderUIColor:(UIColor*)color
{
self.borderColor = color.CGColor;
}
-(UIColor*)borderUIColor
{
return [UIColor colorWithCGColor:self.borderColor];
}
#end
Swift 3
If you want to see the result in IB when you use IBInspectable, you have to extend UIView and add the properties to that class, i.e.
#IBDesignable class MyView: UIView {}
extension MyView {
#IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable var borderColor: UIColor {
get {
return UIColor.init(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue.cgColor
}
}
}
reference: http://nshipster.com/ibinspectable-ibdesignable/
Short answer :
layer.cornerRadius = 10
layer.borderWidth = 1
layer.borderColor = UIColor.blue.cgColor
Long answer :
Rounded Corners UIButton
customUIView.layer.cornerRadius = 10
Border Thickness
pcustomUIView.layer.borderWidth = 1
Border Color
customUIView.layer.borderColor = UIColor.blue.cgColor
you can set your UIButton User Defined Run Time Attributes ie
borderWidth, cornerRadius, borderColor etc. As shown in the image.
Note:- don't use layer. before the attribute name, it will not work.
You can use a piece of code like:
self.addButton.layer.borderColor = [[UIColor greenColor] CGColor];
Please note: addButton is an IBOutlet.

Cocoa Touch: How To Change UIView's Border Color And Thickness?

I saw in the inspector that I can change the background color, but I'd like to also change the border color and thickness, is this possible?
You need to use view's layer to set border property. e.g:
#import <QuartzCore/QuartzCore.h>
...
view.layer.borderColor = [UIColor redColor].CGColor;
view.layer.borderWidth = 3.0f;
You also need to link with QuartzCore.framework to access this functionality.
Xcode 6 update
Since Xcode's newest version there is a better solution to this:
With #IBInspectable you can set Attributes directly from within the Attributes Inspector.
This sets the User Defined Runtime Attributes for you:
There are two approaches to set this up:
Option 1 (with live updating in Storyboard)
Create MyCustomView.
This inherits from UIView.
Set #IBDesignable (this makes the View update live).*
Set your Runtime Attributes (border, etc.) with #IBInspectable
Change your Views Class to MyCustomView
Edit in Attributes Panel and see changes in Storyboard :)
`
#IBDesignable
class MyCustomView: UIView {
#IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
#IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
#IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
}
* #IBDesignable only works when set at the start of class MyCustomView
Option 2 (not working since Swift 1.2, see comments)
Extend your UIView Class:
extension UIView {
#IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
#IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
#IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
}
This way, your default View always has those extra editable fields in Attributes Inspector. Another advantage is that you don't have to change the class to MycustomView every time.
However, one drawback to this is that you will only see your changes when you run your app.
You can also create border with the color of your wish..
view.layer.borderColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0].CGColor;
*r,g,b are the values between 0 to 255.
Add following #IBInspectables in UIView extension
extension UIView {
#IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set(newValue) {
layer.borderWidth = newValue
}
}
#IBInspectable var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(CGColor: color)
}
return nil
}
set(newValue) {
layer.borderColor = newValue?.CGColor
}
}
}
And then you should be able to set borderColor and borderWidth attributes directly from Attribute inspector. See attached image
Attributes Inspector
view.layer.borderWidth = 1.0
view.layer.borderColor = UIColor.lightGray.cgColor
When I use Vladimir's CALayer solution, and on top of the view I have an animation, like a modal UINavigationController dismissing, I see a lot of glitches happening and having drawing performance issues.
So, another way to achieve this, but without the glitches and performance loss, is to make a custom UIView and implement the drawRect message like so:
- (void)drawRect:(CGRect)rect
{
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(contextRef, 1);
CGContextSetRGBStrokeColor(contextRef, 255.0, 255.0, 255.0, 1.0);
CGContextStrokeRect(contextRef, rect);
}
Try this code:
view.layer.borderColor = [UIColor redColor].CGColor;
view.layer.borderWidth= 2.0;
[view setClipsToBounds:YES];
I wouldn't suggest overriding the drawRect due to causing a performance hit.
Instead, I would modify the properties of the class like below (in your custom uiview):
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.layer.borderWidth = 2.f;
self.layer.borderColor = [UIColor redColor].CGColor;
}
return self;
I didn't see any glitches when taking above approach - not sure why putting in the initWithFrame stops these ;-)
I wanted to add this to #marczking's answer (Option 1) as a comment, but my lowly status on StackOverflow is preventing that.
I did a port of #marczking's answer to Objective C. Works like charm, thanks #marczking!
UIView+Border.h:
#import <UIKit/UIKit.h>
IB_DESIGNABLE
#interface UIView (Border)
-(void)setBorderColor:(UIColor *)color;
-(void)setBorderWidth:(CGFloat)width;
-(void)setCornerRadius:(CGFloat)radius;
#end
UIView+Border.m:
#import "UIView+Border.h"
#implementation UIView (Border)
// Note: cannot use synthesize in a Category
-(void)setBorderColor:(UIColor *)color
{
self.layer.borderColor = color.CGColor;
}
-(void)setBorderWidth:(CGFloat)width
{
self.layer.borderWidth = width;
}
-(void)setCornerRadius:(CGFloat)radius
{
self.layer.cornerRadius = radius;
self.layer.masksToBounds = radius > 0;
}
#end
#IBInspectable is working for me on iOS 9 , Swift 2.0
extension UIView {
#IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set(newValue) {
layer.borderWidth = newValue
}
}
#IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set(newValue) {
layer.cornerRadius = newValue
}
}
#IBInspectable var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(CGColor: color)
}
return nil
}
set(newValue) {
layer.borderColor = newValue?.CGColor
}
}
If you didn't want to edit the layer of a UIView, you could always embed the view within another view. The parent view would have its background color set to the border color. It would also be slightly larger, depending upon how wide you want the border to be.
Of course, this only works if your view isn't transparent and you only want a single border color. The OP wanted the border in the view itself, but this may be a viable alternative.
item's border color in swift 4.2:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell_lastOrderId") as! Cell_lastOrder
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.white.cgColor
cell.layer.cornerRadius = 10
If you want to add different border on different sides, may be add a subview with the specific style is a way easy to come up with.
[self.view.layer setBorderColor: [UIColor colorWithRed:0.265 green:0.447 blue:0.767 alpha:1.0f].CGColor];

Resources