我想创建一个圆形按钮.这个按钮应该看起来像一个圆圈.

这个代码给出了圆形矩形按钮.

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame     = CGRectMake(100, 100, 100, 30);
UIImage  *image  = [UIImage imageNamed:@"01.png"];
[button setImage:image forState:UIControlStateNormal];
[image release];

我想出了如何创建一个圆形矩形按钮,但我想创建一个圆形按钮.我需要改变什么?

推荐答案

Tested Code:

H

 #import <QuartzCore/QuartzCoreH>

-(void)roundButtonDidTap:(UIButton*)tappedButton;

M

#define ROUND_BUTTON_WIDTH_HEIGHT YourButtonWidthToBeSetHere

-(void)roundButtonDidTap:(UIButton*)tappedButton{

    NSLog(@"roundButtonDidTap Method Called");

}



UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

[button setImage:[UIImage imageNamed:@"TimoonPumba.png"] forState:UIControlStateNormal];

[button addTarget:self action:@selector(roundButtonDidTap:) forControlEvents:UIControlEventTouchUpInside];

//width and height should be same value
button.frame = CGRectMake(0, 0, ROUND_BUTTON_WIDTH_HEIGHT, ROUND_BUTTON_WIDTH_HEIGHT);

//Clip/Clear the other pieces whichever outside the rounded corner
button.clipsToBounds = YES;

//half of the width
button.layer.cornerRadius = ROUND_BUTTON_WIDTH_HEIGHT/2.0f;
button.layer.borderColor=[UIColor redColor].CGColor;
button.layer.borderWidth=2.0f;

[self.view addSubview:button];

Result

在此处输入图像描述

Geometry in this concept

在此处输入图像描述

Objective-c相关问答推荐

如果DISPATCH_SOURCE_SET_EVENT_HANDLER中的SELF需要为弱

来自 NSDate 的日期名称?

具有自定义视图的相机

如何在 Cocoa 中创建字符串的 MD5 哈希?

UISearchDisplayController 没有结果tableView?

在我的 UIImageView 的子类中没有调用 drawRect

如何使用 NSString drawInRect 使文本居中?

带有 IB_DESIGNABLE 的 UIButton 会引发运行时属性警告,并且不会在 Interface Builder 中呈现

iOS中CALayer的UIImage

Objective-C:集合枚举块中的 continue继续?

何时使用静态字符串与 #define

当单元格全屏时,为什么 UICollectionView 会记录错误?

用于 iOS 开发的 LLVM 与 GCC

强制iphone应用程序以编程方式重新启动?

如何在 UIImageView 中显示 base64 图像?

Objective-C 中的 NSString indexOf

获取最顶层的 UIViewController

判断核心数据中是否存在对象的最快方法?

如何检测父视图控制器中模态视图控制器的解除?

Objective-C in,out,inout,byref,byval, .. 等等.这些是什么?