UIButton在设置Image时,会把之前设置的frame给覆盖掉。

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);

    }];

}

上面输会输出: theImageViewBtn=-{{300, 300}, {10, 10}}


然后运行时, 会发现, 这个按钮的位置大小是后面这个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);

            }];

结果发现按钮的初始大小为768*1024, 不是之前设定的singleRect大小。

要达到上面的期望的效果,需要如下面:

            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(007681024);

            }];


具体原因不知,如有高人路过,麻烦解惑,感激不尽。。。。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值