在界面构建器中设置UIButton图层的边框宽度和颜色

19

我可以使用IB_DESIGNABLE和/或IBInspectable在Interface Builder中设置layer.borderWidth和layer.borderColor吗?我目前是在代码中创建我的按钮,但我希望能够在IB中设置所有这些,但我不确定这些属性是否可以在Xcode 6中以这种方式设置。我想将其设置成IBOutlet,而不是在代码中设置所有内容。以下是我的按钮代码。

directions = [UIButton buttonWithType:UIButtonTypeRoundedRect];
directions.titleLabel.textAlignment = NSTextAlignmentCenter;
directions.titleLabel.font = [UIFont fontWithName:@"FranklinGothicStd-ExtraCond" size:20.0];
[directions setTitle:@"Directions" forState:UIControlStateNormal];
[directions setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
directions.frame = CGRectMake(20, 178, 70, 70);
directions.layer.borderWidth = 2.0f;
directions.layer.borderColor = [UIColor whiteColor].CGColor;
directions.clipsToBounds = YES;
directions.backgroundColor = [UIColor clearColor];
[directions addTarget:self action:@selector(getDirections:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:directions];

我按照建议设置了这些值,但边框在模拟器中没有显示出来。 编辑:我发现当我在IB中设置这些值时,边框未显示出来的原因是边框颜色是一个CGColor,所以我必须在代码中设置它。

3个回答

35
实际上,您可以通过界面构建器设置视图层的某些属性。我知道我可以通过Xcode设置图层的borderWidth和cornerRadius。borderColor不起作用,可能是因为图层需要一个CGColor而不是UIColor。
您可能需要使用字符串而不是数字,但它有效!

enter image description here

但你可以使用类别来代理诸如layer.borderColor之类的属性。(来自ConventionalC CocoaPod)

CALayer+XibConfiguration.h:

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface CALayer(XibConfiguration)

// This assigns a CGColor to borderColor.
@property(nonatomic, assign) UIColor* borderUIColor;

@end

CALayer+XibConfiguration.m:

#import "CALayer+XibConfiguration.h"

@implementation CALayer(XibConfiguration)

-(void)setBorderUIColor:(UIColor*)color
{
    self.borderColor = color.CGColor;
}

-(UIColor*)borderUIColor
{
    return [UIColor colorWithCGColor:self.borderColor];
}

@end

Interface Builder

结果将在运行时显示,而不是在Xcode中。


2
对于其他人来说,如果你想要 Swift 版本,请查看:https://dev59.com/8mUq5IYBdhLWcg3wF8nw#27986696 - RyanJM
看起来在 Xcode 7.3 中可以使用数字值在用户定义的运行时属性中设置 cornerRadius。 - Tom Howard
如何设置此代理 - Amr Angry
很简单。创建一个名为CALayer+XibConfiguration.h的类,将上述代码写入该类中。这样就完成了。现在你可以在Interface Builder中使用它的运行时属性了。 - Baig

5
您可以在界面构建器中通过添加运行时属性来设置大多数内容的值: enter image description here 例如,对于 layer.borderWidth = 2.0f; 的设置方法如下:
选择按钮并添加新属性, keypath:layer.borderWidth, type: Number, value: 2。
这些更改不会在界面构建器内显示,只有在运行时才会看到。

谢谢。这很有帮助,但我想了解如何使用IBInspectable和IB_DESIGNABLE,以便在IB中可以看到效果。 - raginggoat
你还需要设置borderColor来显示边框。 - Istvan
请查看我的问题更新。我已经设置了边框颜色。 - raginggoat

5

是的,您可以在右侧单击身份验证器,在那里找到如下内容

enter image description here

User Defined Runtime Attributes中单击+

选择keypath并编辑它

像这样编写代码

layer.cornerRadius,在Type中将类型更改为number,并设置所需值,如下所示

您也可以更改文本颜色等。

愉快的编程


谢谢。这很有帮助,但我想知道如何使用IBInspectable和IB_DESIGNABLE,以便在IB中可以看到效果。 - raginggoat
我刚刚尝试了这个,边框没有出现。 - raginggoat
你需要设置 [button.layer setMasksToBounds:YES]; - sreekanthk
我刚刚尝试设置了那个,但边框仍然没有显示。 - raginggoat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接