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


当前回答

当我使用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);    
}

其他回答

(self。view。layer setBorderColor: [uicolcolorwithred:0.265 green:0.447 blue:0.767 alpha:1.0f].CGColor];

如果你想在不同的边线上添加不同的边框,可能添加一个带有特定样式的子视图是一种容易想出的方法。

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

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

在UIView扩展中添加以下@IBInspectables

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
    }
  }
}

然后你应该能够从属性检查器中直接设置borderColor和borderWidth属性。见附图

属性检查器

我不建议重写drawRect,因为这会导致性能下降。

相反,我将修改类的属性如下(在你的自定义uiview):

  - (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
      self.layer.borderWidth = 2.f;
      self.layer.borderColor = [UIColor redColor].CGColor;
    }
  return self;

当采用上述方法时,我没有看到任何故障-不确定为什么放入initWithFrame会停止这些;-)