Objective-C新手的位,我环顾四周寻找答案,但一直未能找到一个如此原谅我,如果这是一个明显的问题。继承UIView - 丢失实例变量
基本上,我需要绘制一个圆的屏幕段(例如,一个90度的段,其中水平线和垂直线在左下方相交并且一条圆弧连接终点)。我设法在一个名为CircleSegment的自定义类中实现此功能,该类继承UIView并覆盖drawRect
。
我的问题是实现这个编程;我需要一些创建CircleSegment类的方法,并在之前存储它所需的角度,它会绘制段本身。
这是我到目前为止有:
CircleSegment.h
#import <UIKit/UIKit.h>
@interface CircleSegment : UIView {
float angleSize;
UIColor *backColor;
}
-(float)convertDegToRad:(float)degrees;
-(float)convertRadToDeg:(float)radians;
@property (nonatomic) float angleSize;
@property (nonatomic, retain) UIColor *backColor;
@end
CircleSegment.m
#import "CircleSegment.h"
@implementation CircleSegment
@synthesize angleSize;
@synthesize backColor;
// INITIALISATION OVERRIDES
// ------------------------
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
self.opaque = NO;
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)setBackgroundColor:(UIColor *)newBGColor
{
// Ignore.
}
- (void)setOpaque:(BOOL)newIsOpaque
{
// Ignore.
}
// MATH FUNCTIONS
// --------------
// Converts degrees to radians.
-(float)convertDegToRad:(float)degrees {
return degrees * M_PI/180;
}
// Converts radians to degrees.
-(float)convertRadToDeg:(float)radians {
return radians * 180/M_PI;
}
// DRAWING CODE
// ------------
- (void)drawRect:(CGRect)rect {
float endAngle = 360 - angleSize;
UIBezierPath* aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100)
radius:100
startAngle:[self convertDegToRad:270]
endAngle:[self convertDegToRad:endAngle]
clockwise:YES];
[aPath addLineToPoint:CGPointMake(100.0, 100.0)];
[aPath closePath];
CGContextRef aRef = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(aRef, backColor.CGColor);
CGContextSaveGState(aRef);
aPath.lineWidth = 1;
[aPath fill];
[aPath stroke];
//CGContextRestoreGState(aRef);
}
- (void)dealloc {
[super dealloc];
}
@end
注意,.m文件是有点乱用各种测试代码位...
所以基本上我想创建一个CircleSegment的实例,在angleSize属性中存储一个角度,根据该角度绘制一个线段,然后将该视图添加到主应用视图以显示它...
尝试而做到这一点,我已经添加下面的测试代码viewDidLoad
在我的ViewController:
CircleSegment *seg1 = [[CircleSegment alloc] init];
seg1.backColor = [UIColor greenColor];
seg1.angleSize = 10;
[self.view addSubview:seg1];
看来存储的UIColor和angleSize很好,当我断点那些地方,但是如果我把一个断点在drawRect
我在CircleSegment.m上覆盖,这些值已恢复为零值(或任何正确的术语将是,请随时纠正我)。
我真的很感激,如果有人能指出我在正确的方向!
谢谢
Aaaaaack,你完全正确。我会使用界面生成器将CircleSegment拖到我的ViewController上,并且我的断点首先触击了_that_实例。这很烦人,你可能会错过简单的事情。所有的工作现在,谢谢! – Rich 2010-12-21 18:08:58