【问题标题】:iOS: DrawRect does not move my viewiOS:DrawRect 不会移动我的视图
【发布时间】:2014-04-04 06:50:35
【问题描述】:

我是 iOS 上的新开发人员,我正在努力使用 DrawRect 方法:第一次调用它时,它实际上在我想要的地方绘制了我想要的东西,但是接下来对 DrawRect 的所有调用都无法移动我的视图(尽管他们确实调整了它的大小)。
因此,我制作了一个极简测试应用程序来重现我的问题,但仍然无法找出原因。
这个应用程序只是在左上角绘制了一个蓝色矩形,每次点击它时,它应该:

  • 切换宽度和高度(这确实有效)
  • 将矩形向右移动 10 点(这不起作用

当然,我检查了 DrawRect 确实被调用了,并且它的边界确实改变了我想要的,但是我的视图仍然不想移动。

=============================================== 这是我的 ViewController (RVTViewController.m)
================================================

@implementation RVTViewController
(void)viewDidLoad`
{
    [super viewDidLoad];
    if (!self.myView)
    {
        CGRect viewBounds = CGRectMake(0,0,100,150);
        self.myView = [[RVTView alloc] initWithFrame:viewBounds];
        [self.view addSubview:self.myView];        
        UITapGestureRecognizer* gestRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [self.myView addGestureRecognizer:gestRec];
    }
}

-(void) tap:(UITapGestureRecognizer*) gesture
{
    CGRect newViewBounds = CGRectMake(self.myView.bounds.origin.x + 10,
                                      self.myView.bounds.origin.y,
                                      self.myView.bounds.size.height,
                                      self.myView.bounds.size.width);
    self.myView.bounds = newViewBounds;
    [self.myView setNeedsLayout]; 
    [self.myView setNeedsDisplay];
}
@end

======================================
这是我的自定义视图 (RVTView.m)
======================================

@implementation RVTView
- (void)drawRect:(CGRect)rect
{
    CGRect newBounds = self.bounds;
    UIBezierPath* newRect = [UIBezierPath bezierPathWithRect:newBounds];
    [[UIColor blueColor] setFill];
    UIRectFill(self.bounds);
    [newRect stroke];
}
@end

谁能告诉我我做错了什么?

【问题讨论】:

  • 你真的想改变视图的框架而不是边界吗? Bounds 是视图的内部几何形状,而 frame 是其父视图坐标系中的位置和大小。
  • 你只想改变每次点击对应的view的x坐标和宽高,对吧?
  • 是的,完全正确。非常感谢您的评论。所以我明白我将使用“框架”而不是“边界”。实际上使用“setFrame”正是我想要的。非常感谢大家。

标签: ios objective-c uiviewanimation drawrect


【解决方案1】:

使用[self.myView setFrame:newViewBounds]; 而不是self.myView.bounds = newViewBounds; 解决了这个问题。

【讨论】:

    猜你喜欢
    • 2010-12-30
    • 2011-07-30
    • 2016-04-06
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 2016-04-13
    • 2020-02-18
    • 2017-09-08
    相关资源
    最近更新 更多