iOS7选择按钮边框效果

标签 ios objective-c iphone ios7 uibutton

所以我是 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或通过代码获得相同的初始化)。

之后只需将按钮自定义类配置为“按下按钮类”即可 enter image description here

如果您需要更多帮助,请随时询问 :)

关于iOS7选择按钮边框效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530542/

相关文章:

php - sUrl 和 fUrl 应该是什么 - PayU Money iOS 集成

objective-c - 使用 AVAudioPlayer 框架完成播放后,如何再次播放相同的声音?

ios - 带有背景图像的 UItableviewcells 没有填满屏幕的整个宽度?

iphone - 使用 AudioStreamer 获取 MP3 ID3 元数据和歌曲持续时间

iphone - 如何在iPhone的UIView中添加边界轮廓,请阅读说明

ios - 尝试设置 UILabel 的文本时,结果始终为 'Optional("0. 0")'

ios - trackWithMediaType 有时返回 0 首轨道

ios - 如何为 UICollectionViewCell 创建阴影

ios - objective-c 比较两个CGPoint以查看它们是否接近?

ios - 带有分数的 NSDecimalNumber 在提升到高幂时返回大数?