简体   繁体   中英

How to change UIButton frame to fit the image inside in IOS?

I have created a button in storyboard with an image. When highlighted(touched), I want this button to change image with a larger one and resize according to new image. Storyboard is set and here is my code for touch up inside event:

if(self.testButton.state == UIControlStateHighlighted)
{
    self.testButton.frame = CGRectMake(100, 20, 120, 145);
    self.testButton.contentMode = UIViewContentModeScaleAspectFill;
}
NSLog(@"End Frame: ( %f %f %f %f )", self.testButton.frame.origin.x, self.testButton.frame.origin.y, self.testButton.frame.size.width, self.testButton.frame.size.height );

but my frame size does not change. My question

1.Can I solve this with storyboard?
2.How can I solve this with code?

Declare buttonFrame as instance variable and add targets.

CGRect buttonFrame;

[self.testButton addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];
[self.testButton addTarget:self action:@selector(touchUp) forControlEvents:UIControlEventTouchUpInside];
}

- (void)touchDown
{
    buttonFrame = self.testButton.frame;
    self.testButton.frame = CGRectMake(self.testButton.frame.origin.x, self.testButton.frame.origin.y, 120, 145);
    self.testButton.contentMode = UIViewContentModeScaleAspectFill;
}

- (void)touchUp
{
    self.testButton.frame = buttonFrame;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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