2011-02-18 49 views
148

我有一个矩形图像(jpg),并希望用它来填充xcode中具有圆角的按钮的背景。如何绕一个按钮的角落

我写了下面:

UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain]; 
CGRect frame = CGRectMake(x, y, cardWidth, cardHeight); 
button.frame = frame; 
[button setBackgroundImage:backImage forState:UIControlStateNormal]; 

然而,按钮,我用这种方法得到不具有其边角圆润:这是不是一个普通的矩形长相酷似我的原始图像。我怎样才能得到一个圆角的图像来代表我的按钮?

谢谢!

回答

385

我想我得到了你的问题,我试着用UITextArea以下解决方案,我想这也适用于UIButton。

首先进口这在你的.m文件 -

#import <QuartzCore/QuartzCore.h> 

,然后在loadView方法中添加以下行

yourButton.layer.cornerRadius = 10; // this value vary as per your desire 
    yourButton.clipsToBounds = YES; 

希望这对你的作品,如果是做沟通。

+1

非常感谢。这不仅是我需要的,但是你回答了我的下一个问题,那就是确定角落半径是否可以调整。 – double07 2011-02-21 22:57:38

+5

非常感谢 - 尤其是对于clipsToBounds提示。 – Chris 2012-08-01 01:56:02

2

如果你想有一个圆角只有一个角落或两个角,等...阅读岗位:

[ObjC] - 的UIButton与圆角 - http://goo.gl/kfzvKP

这是一个XIB /故事板的子类。无需编写代码即可导入和设置边框。

6

进口QuartCore框架,如果它不存在于现有的项目,然后导入#import <QuartzCore/QuartzCore.h>viewcontroller.m

UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect]]; 
CGRect frame = CGRectMake(x, y, width, height); // set values as per your requirement 
button.layer.cornerRadius = 10; 
button.clipsToBounds = YES; 
94

可以实现通过这种运行属性

enter image description here

我们可以自定义button.just看附加的截图。

亲切注意:

在运行时的属性来改变边框的颜色按照此说明

  1. 创建.h文件类别类的CALayer

  2. @property(nonatomic, assign) UIColor* borderIBColor; 
    
  3. 在M档

    -(void)setBorderIBColor:(UIColor*)color { 
        self.borderColor = color.CGColor; 
    } 
    
    -(UIColor*)borderIBColor { 
        return [UIColor colorWithCGColor:self.borderColor]; 
    } 
    

现在开始设置边框颜色检查截图

updated answer

感谢

11

你可能想看看我的库调用DCKit 。它写在最新版本Swift

你会能够使圆角按钮/文本字段直接从界面生成器:

DCKit: rounded button

它也有其他许多很酷的功能,如使用验证文本字段,以控制边框,边框虚线,圆,发际等意见

6

推到了极限圆角半径达得到一个圆:

self.btnFoldButton.layer.cornerRadius = self.btnFoldButton.frame.height/2.0; 

enter image description here

如果按钮框是一个正方形,那么frame.height或frame.width无关紧要。否则使用两者中最大的一个。

4
UIButton* closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 50, 90, 35)]; 
//Customise this button as you wish then 
closeBtn.layer.cornerRadius = 10; 
closeBtn.layer.masksToBounds = YES;//Important 
1

第一设定宽度= 100和高度按钮

YourBtn1.layer.cornerRadius=YourBtn1.Frame.size.width/2; 
YourBtn1.layer.borderColor=[uicolor blackColor].CGColor; 
YourBtn1.layer.borderWidth=1.0f; 
1

的= 100的SWIFT:

button.layer.cornerRadius = 10.0 
2

更新的夫特3:

下面使用代码使UIButton转角:

yourButtonOutletName.layer.cornerRadius = 0.3 * 
     yourButtonOutletName.frame.size.height