ios Cocoa Touch:如何更改 UIView 的边框颜色和粗细?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3330378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:27:04  来源:igfitidea点击:

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

iosobjective-ciphonecocoa-touchinterface-builder

提问by foreyez

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?

我在检查器中看到我可以更改背景颜色,但我还想更改边框颜色和粗细,这可能吗?

回答by Vladimir

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.

您还需要链接 QuartzCore.framework 以访问此功能。

回答by MMachinegun

Xcode 6 update

Xcode 6 更新

Since Xcode's newest version there is a better solution to this:

由于 Xcode 的最新版本有一个更好的解决方案:

With @IBInspectableyou can set Attributes directly from withinthe Attributes Inspector.

随着@IBInspectable您可以直接设置属性Attributes Inspector

My Custom View @IBInspectable Attributes

我的自定义视图 @IBInspectable 属性

This sets the User Defined Runtime Attributesfor you:

User Defined Runtime Attributes为您设置:

enter image description here

在此处输入图片说明

There are two approaches to set this up:

有两种设置方法:

Option 1(with live updating in Storyboard)

选项 1(在 Storyboard 中实时更新)

  1. Create MyCustomView.
  2. This inherits from UIView.
  3. Set @IBDesignable(this makes the View update live).*
  4. Set your Runtime Attributes (border, etc.) with @IBInspectable
  5. Change your Views Class to MyCustomView
  6. Edit in Attributes Panel and see changes in Storyboard :)
  1. 创建MyCustomView.
  2. 这继承自UIView.
  3. 设置@IBDesignable(这会使视图更新生效)。*
  4. 设置您的运行时属性(边框等) @IBInspectable
  5. 将您的视图类更改为 MyCustomView
  6. 在属性面板中编辑并查看故事板中的更改:)

`

`

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

* @IBDesignableonly works when set at the start of class MyCustomView

*@IBDesignable仅在开始时设置时有效class MyCustomView

Option 2(not working since Swift 1.2, see comments)

选项 2(自 Swift 1.2 起不起作用,请参阅评论)

Extend your UIView Class:

扩展你的 UIView 类:

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 alwayshas those extra editable fields in Attributes Inspector. Another advantage is that you don't have to change the class to MycustomViewevery time. However, one drawback to this is that you will only see your changes when you run your app.

这样,您的默认视图始终Attributes Inspector. 另一个优点是您不必MycustomView每次都将类更改为。但是,这样做的一个缺点是只有在运行应用程序时才能看到更改。

回答by rohan-patel

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.

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

回答by Bikramjit Singh

Add following @IBInspectables in UIView extension

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

And then you should be able to set borderColor and borderWidth attributes directly from Attribute inspector. See attached image

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

Attributes Inspector

属性检查器

回答by shaiju mathew

view.layer.borderWidth = 1.0
view.layer.borderColor = UIColor.lightGray.cgColor

回答by Nicu Surdu

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.

当我使用 Vladimir 的 CALayer 解决方案时,并且在视图之上我有一个动画,比如模态 UINavigationController 关闭,我看到很多小故障发生并有绘图性能问题。

So, another way to achieve this, but without the glitches and performance loss, is to make a custom UIView and implement the drawRectmessage like so:

因此,实现此目的的另一种方法是制作自定义 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);    
}

回答by Vikram Biwal

Try this code:

试试这个代码:

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

回答by DEzra

I wouldn't suggest overriding the drawRect due to causing a performance hit.

由于会导致性能下降,我不建议覆盖 drawRect。

Instead, I would modify the properties of the class like below (in your custom uiview):

相反,我会修改类的属性,如下所示(在您的自定义 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 ;-)

采取上述方法时我没有看到任何故障 - 不知道为什么放入 initWithFrame 会阻止这些 ;-)

回答by spencery2

I wanted to add this to @marczking's answer (Option 1) as a comment, but my lowly status on StackOverflow is preventing that.

我想将此添加到@marczking 的答案(选项 1)中作为评论,但我在 StackOverflow 上的低地位阻止了这一点。

I did a port of @marczking's answer to Objective C. Works like charm, thanks @marczking!

我做了一个@marczking 对 Objective C 的回答的移植。像魅力一样工作,谢谢@marczking!

UIView+Border.h:

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:

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

回答by anhtran

@IBInspectable is working for me on iOS 9 , Swift 2.0

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