afi*_*fin 12 iphone cocoa-touch objective-c
我试图将图像设置为自定义UIButton的背景.我能够在界面构建器中为"圆角矩形"UIButton设置背景图像,但现在边框已经消失.有没有办法保留边界?此外,我想使边框显示矩形而不是圆角.
tri*_*ons 43
#import <QuartzCore/QuartzCore.h> // don't forget to add this in your file
CALayer * layer = [yourUIButton layer];
[layer setMasksToBounds:YES];
[layer setCornerRadius:0.0]; //when radius is 0, the border is a rectangle
[layer setBorderWidth:1.0];
[layer setBorderColor:[[UIColor grayColor] CGColor]];
Run Code Online (Sandbox Code Playgroud)
我知道这是一个老问题,但我仍然想在这里发表我的答案.因为我正在寻找答案,但这让我自己解决了一个简单的方法.
Jon*_*ast 17
看看cornerRadius,borderWidth和borderColor属性CALayer.这些属性是iPhone OS 3.0的新功能.
您可能想要子类化UIButton,然后在构造函数中设置这些属性.您的按钮具有图层属性,您可以访问该属性来设置这些边框属性.
这是一个例子:
- (id)initWithFrame:(CGRect)frame {
if(self = [super initWithFrame:frame]) {
[self.layer setBorderWidth:1.0];
[self.layer setCornerRadius:5.0];
[self.layer setBorderColor:[[UIColor colorWithWhite:0.3 alpha:0.7] CGColor]];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
我想补充一下nanshi和Jonathan提供的答案.
为了访问border和cornerRadius图层的属性,你首先需要导入QuartzCore框架.
#import <QuartzCore/QuartzCore.h>
否则您将无法访问这些属性.
当您在按钮中设置背景图像时,按钮轮廓会消失。将它们包含在您的图像中,如果您需要不同的尺寸,请查看 UIImage
stretchableImageWithLeftCapWidth:topCapHeight:
方法。