UIButton Set ImageView Frame

Source: Internet
Author: User

We found that when setting a frame for the UIButton ImageView, the size of the image cannot be changed, the size is the size of the picture, and the position can be modified using the Imageedgeinsets property.

Principle: Modifying the UIButton ImageView frame will call Superview, UIButton-(void) layoutsubviews, and this layoutsubviews will invoke UIButton's

-(CGRect) Imagerectforcontentrect: (CGRect) Contentrect; method, which returns the size of the picture by default.


There are several ways to modify the ImageView frame, which I think of:

1. Rewrite-(CGRect) Imagerectforcontentrect: (CGRect) Contentrect;

2. Delete ImageView view, add new ImageView, control frame

3. Rewrite layoutsubviews

-(void) layoutsubviews

{

cgrect frame = self. ImageView . Frame ;

[super layoutsubviews];

Self. ImageView . Frame = frame;

}

4. Do not inherit UIButton, directly modify the default implementation of Layoutsubviews

void Layoutsubviewswithoutautosetimageviewframe (ID self, Sel Sel)

{

UIButton * btn = (uibutton*)self;

cgrect frame;

if (btn. ImageView )

    {

frame = btn. ImageView . Frame ;

    }

[btn performselector:@selector(oldlayoutsubviews)];

if (btn. ImageView )

    {

btn. ImageView . Frame = frame;

    }

}


void Replaceuibuttonlayoutsubviewsmethod ()

{

IMP layoutsubviewsimp = class_getmethodimplementation([UIButton class], @selector (layoutsubviews));

class_addmethod([uibutton class], @selector (oldlayoutsubviews), Layoutsubviewsimp, "v@:" );

class_replacemethod([uibutton class], @ Selector(layoutsubviews), (IMP) ( Layoutsubviewswithoutautosetimageviewframe), "v@:");

}

Welcome everyone to spend the problem, discuss together, progress together, thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.