50

I'm looking to have a border around a UIView I have just to separate it from the main view visually.

I have looked in the settings for the UIView in storyboard editor but I can't seem to find anything for setting a border.

Is there an easy way to do this in code?

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
user1282180
  • 1,103
  • 3
  • 11
  • 20
  • 2
    possible duplicate of [Cocoa Touch: How To Change UIView's Border Color And Thickness?](http://stackoverflow.com/questions/3330378/cocoa-touch-how-to-change-uiviews-border-color-and-thickness) – Andrew Jun 10 '14 at 16:40

2 Answers2

29

With Swift and XCode 6 you can do this.

Click the UIView element in Storyboard, and go to identity inspector. In the user defined runtime attributes, enter:

layer.borderWidth number 1

If you want nice looking corners

layer.cornerRadius number 5
layer.masksToBounds boolean true

Now this will give you a border but to set the colour you need to do it with code. Go to your view controller, and add an IBOutlet from your UIView. Say you do,

@IBOutlet weak var xView: UIView!

Call this in the viewDidLoad function like below to set the colour.

xView.layer.borderColor = UIColor.whiteColor().CGColor

Thanks!

pkamb
  • 33,281
  • 23
  • 160
  • 191
mtisz
  • 1,000
  • 10
  • 11
  • why do you have to define the color in code? There is the field `layer.borderColor color red`, but that does not work. Can you explain why? – MMachinegun Mar 10 '15 at 18:08
  • I found a way how the color does update in storyboard :) See my answer http://stackoverflow.com/a/29074130 – MMachinegun Mar 16 '15 at 10:11
1

With this border, background still appears behind. In other words, the border isn't projected to outer of view, but to inner space.

I think that is necessary create a overlay view behind the owner with size (width x height) increased with border size.

seufagner
  • 21
  • 4