我在检查器中看到我可以改变背景颜色,但是我想改变边框的颜色和粗细,可以吗?


当前回答

当我使用Vladimir的CALayer解决方案时,在视图的顶部我有一个动画,像一个模态UINavigationController解散,我看到很多故障发生,并有绘图性能问题。

另一种实现这个的方法,但是没有小故障和性能损失,是创建一个自定义UIView并实现drawRect消息,像这样:

- (void)drawRect:(CGRect)rect
{
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(contextRef, 1);
    CGContextSetRGBStrokeColor(contextRef, 255.0, 255.0, 255.0, 1.0);
    CGContextStrokeRect(contextRef, rect);    
}

其他回答

试试下面的代码:

view.layer.borderColor =  [UIColor redColor].CGColor;
view.layer.borderWidth= 2.0;
[view setClipsToBounds:YES];

我想把这个添加到@marczking的答案(选项1)作为评论,但我在StackOverflow上的低级状态阻止了这一点。

我把@marczking对Objective c的回答做了一个移植,非常有魅力,谢谢@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

如果你不想编辑UIView的层,你总是可以将视图嵌入到另一个视图中。父视图将其背景颜色设置为边框颜色。它也会稍微大一点,这取决于你想要的边界有多宽。

当然,这只适用于你的视图不是透明的,你只想要一个单一的边界颜色。OP希望在视图本身的边界,但这可能是一个可行的替代方案。

你也可以创建边界的颜色你的愿望..

view.layer.borderColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0].CGColor;

*r,g,b是0到255之间的值。

@IBInspectable在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
    }
}