所以我是 iOS 的新手,我想要一些带有圆形边框的按钮。当选择按钮时,我还希望这些边框与按钮内的文本具有相同的效果。
由于 roundRect 按钮不再是 iOS 中的对象(或者至少我找不到它,而且我读到的所有地方都说它不再存在)我决定编写一个扩展 UIButton 的自定义类。这是我的:
- (void)drawRect:(CGRect)rect{
{
UIColor *blackColor = blackColor;
UIColor *transBlack = [blackColor colorWithAlphaComponent:(0.5)];
[self.layer setCornerRadius:10.0f];
[self.layer setBorderColor:[UIColor blackColor].CGColor];
[self.layer setBorderWidth:1.0];
if(self.isSelected){
[self.layer setBorderColor:(transBlack.CGColor)];
}
我不确定我是否正确使用了 isSelected。我在它下面有一个 NSLog,无论我按下按钮多少次,它似乎都不会被执行。
如有任何帮助和建议,我们将不胜感激。谢谢。
最佳答案
UIButton 继承自 UIView,所以你可以使用 Layer 的方法... 创建新的对象,子类化 UIButton 可以随意调用它,然后实现下一个代码: 在此示例中,我在 .m 文件中有一个名为 PressedButton 的 UIButton 子类:
@implementation PressedButton
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
//When the button is pressed the border color change to red
self.layer.borderColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5].CGColor;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
//When the button is pressed the border color change back to black
self.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5].CGColor;
}
- (void)initialize{
self.layer.cornerRadius = 10.0f;
self.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5].CGColor;
self.layer.borderWidth = 2;
self.layer.masksToBounds = YES;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
[self initialize];
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self initialize];
}
return self;
}
- (instancetype)init
{
self = [super init];
if (self) {
[self initialize];
}
return self;
}
@end
*** 我实现了所有初始化方法,以确保无论我在哪里设置按钮( Storyboard或通过代码获得相同的初始化)。
之后只需将按钮自定义类配置为“按下按钮类”即可
如果您需要更多帮助,请随时询问 :)
关于iOS7选择按钮边框效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530542/