简体   繁体   English

UIView setNeedsDisplay不起作用

[英]UIView setNeedsDisplay doesn't work

Simple code is here: 简单的代码在这里:

Custom MyButton.h 自定义MyButton.h

@interface PaiLifeReadingListButton : UIButton
@property (strong, nonatomic) UIImageView *logoImageView;
@end

Custom MyButton.m 自定义MyButton.m

@implementation PaiLifeReadingListButton
@synthesize logoImageView = _logoImageView;
-(id)init
{
    _logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(33.0, 20.0, 80.0, 80.0)];
    [_logoImageView setImage:[UIImage imageNamed:@"pic"]];
    [self addSubview: _logoImageView];
}  
@end

Custom MyView.h: 自定义MyView.h:

@property (strong, nonatomic) Mybutton *mybutton;

Custom MyView.m: 自定义MyView.m:

-(id) init
{
    myButton = [[MyButton alloc] init];
    [self addSubview:myButton];
}

ViewController.m: ViewController.m:

@synthesize myView;
- (void)viewDidLoad
{
    myView = [[Myview alloc] init];
    [myView.myButton addTarget:self action:@selector(pressed:) forControlEvents:UIControlEventTouchDown];
    self.view = myView;
}
-(void)pressed : (MyButton *)button
{
    UIImageView *newImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"other-pic"] highlightedImage:nil];
    myView.myButton.logImageView = newImageView;
    [self.view setNeedsDisplay]; //----this does not work
}

When I press the button, the imageview does not change. 当我按下按钮时,imageview不会改变。 How can I fix this? 我怎样才能解决这个问题? Thank you very much! 非常感谢你!

First thing , you don't need setNeedsDisplay here. 第一件事,这里不需要setNeedsDisplay setNeedsDisplay is used for redrawing the view (it internally calls the drawRect: method of the view if required) which is not what you want. setNeedsDisplay用于重新绘制视图(如果需要,它在内部调用视图的drawRect:方法)。

Second, you have given the class of your button as MyButton ,but in the actual .h and .m files, it is given as @interface PaiLifeReadingListButton and @implementation PaiLifeReadingListButton respectively. 其次,您将按钮的类别指定为MyButton ,但在实际的.h和.m文件中,分别将其命名为@interface PaiLifeReadingListButton@implementation PaiLifeReadingListButton

Another thing, the view and button is not initialized with a frame. 另一件事,视图和按钮未使用框架初始化。 But I assume you have done that already, since your only problem is the image view not changing. 但是我认为您已经这样做了,因为您唯一的问题是图像视图没有改变。

In your code in pressed method you should change views in the hierarchy, but you change only the object member. 在按下方法的代码中,您应该更改层次结构中的视图,但是只能更改对象成员。 You can do something like 你可以做类似的事情

myView.myButton.logImageView.image = [UIImage imageNamed:@"other-pic"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM