UIButton, setImage 会自动设置这个按钮的frame为这个图的大小,会使之前设置的这个按钮的frame无效
一下午的折腾,被这个问题搞得头大。
基本需求是:
一个UIView Animation 动画, 点击某一个区域, 动画是从该区域弹出一张小图, 小图慢慢放大到全屏成为大图至全屏,
为此, 我们想在在该区域弹出的一个小图,用一个按钮来做, 然后把这个按钮放大到全屏, 最后用户点击这个按钮后,把自己给remove掉。
于是代码如下:
// 下面是点击那个小区域所触发的操作。这里先设置了frame然后再设置image, 就会出现上述所说的问题。但是奇怪的是,如果这个按钮theImageViewBtn在之前,比如在viewDidLoad时,就已经初始化好了,并设置好图片和大小,则不会有下面的问题。只在在点击事件中,重新生成一个新的按钮,并使该铵钮触发事件,才会出现上述的问题。
// 下面这个go.png为320*460大小。
- (void)fangDaBtnClicked:(id)sender {
UIButton *theImageViewBtn = [UIButtonbuttonWithType:UIButtonTypeCustom];
theImageViewBtn.frame =CGRectMake(300,300, 10, 10);
[theImageViewBtn setImage:[UIImageimageNamed:@"go.png"]forState:UIControlStateNormal];
NSLog(@"theImageViewBtn=-%@", NSStringFromCGRect(theImageViewBtn.frame));
[self.viewaddSubview:theImageViewBtn];
[UIViewanimateWithDuration:0.5animations:^{
seconBnt.frame = CGRectMake(0, 0, 320, 460);
}];
}
然后运行时, 会发现, 这个按钮的位置大小是后面这个UIImage的默认大小。而不是前行代码设置的frame, 所以正常的代码需要先写setImage然后再设置这个按钮的frame值。
UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
clickBtn.frame = singleRect; // 这里设置过一次frame
[clickBtn setImage:showedImage forState:UIControlStateNormal]; // 然后再设置这个大图
clickBtn.frame = singleRect;
[clickBtn addTarget:self action:@selector(imageBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:clickBtn]; // 然后再添加进来
// 让这个按钮放大到全屏
[UIView animateWithDuration:0.5 animations:^{
clickBtn.frame = CGRectMake(0, 0, 768, 1024);
}];
要达到上面的期望的效果,需要如下面:
UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[clickBtn setImage:showedImage forState:UIControlStateNormal]; // 设置这个大图
clickBtn.frame = singleRect;
[clickBtn addTarget:self action:@selector(imageBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:clickBtn]; // 然后再添加进来
// 让这个按钮放大到全屏
[UIView animateWithDuration:0.5 animations:^{
clickBtn.frame = CGRectMake(0, 0, 768, 1024);
}];
具体原因不知,如有高人路过,麻烦解惑,感激不尽。。。。