Cocoa Touch: How to Change Uiview's Border Color and Thickness

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

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.

How to set the custom border color of UIView programmatically?

If you Use Swift 2.0+

self.yourView.layer.borderWidth = 1
self.yourView.layer.borderColor = UIColor(red:222/255, green:225/255, blue:227/255, alpha: 1).cgColor

How to change border color of UIview?

Don't use UITapGestureRecognizer. You can use UILongPressGestureRecognizer

Code:

   override func viewDidLoad() {
super.viewDidLoad()

let view = UIView.init(frame: CGRect.init(x: 30, y: 200, width: 100, height: 40))
self.view.addSubview(view)
view.layer.borderColor = UIColor.black.cgColor
view.layer.borderWidth = 3
let tapForView = UILongPressGestureRecognizer(target: self, action: #selector(self.toChangeColor(recognizer:)))
tapForView.minimumPressDuration = 0.01
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tapForView)
}

@objc func toChangeColor(recognizer:UILongPressGestureRecognizer)
{
// Apply logic for changing background color.
let view = recognizer.view
if recognizer.state == .began {
view?.layer.borderColor = UIColor.orange.cgColor
print("view began")
}
else if recognizer.state == .ended {
view?.layer.borderColor = UIColor.black.cgColor
print("view ended")

}

}

This will work perfectly.

Is it possible to set UIView border properties from interface builder?

Actually you can set some properties of a view's layer through interface builder. I know that I can set a layer's borderWidth and cornerRadius through xcode. borderColor doesn't work, probably because the layer wants a CGColor instead of a UIColor.

You might have to use Strings instead of numbers, but it works!

layer.cornerRadius
layer.borderWidth
layer.borderColor

Update:
layer.masksToBounds = true

example

Update:
select appropriate Type for Keypath:

Sample Image

UIView's border color in Interface builder doesn't work?

It's possible to do this, but it's not a built-in feature. This is because the Color type in the User Defined Runtime Attributes panel creates a UIColor, but layer.borderColor holds a CGColorRef type. Unfortunately, there's no way to assign a CGColorRef type in Interface Builder.

However, this is possible through a proxy property. See Peter DeWeese's answer to a different question for a possible solution to this problem. His answer defines a category that allows a proxy color to be set through Interface Builder.



Related Topics



Leave a reply



Submit