iOS >> UIButton ImageView Property >> How to set Content Mode?

后端 未结 3 541
北荒
北荒 2020-12-29 12:05

Is there a way to set a UIButton Image, BackgroundImage or ImageView Properties Content Mode Property?

I\'ve tried the direct approach (it didn\'t work, of course...

3条回答
  •  Happy的楠姐
    2020-12-29 12:25

    Using iOS7/8 with auto-layout, button.imageView doesn't get scaled when button is laid out, e.g. for iPhone 6:

    (lldb) po button
    >
    
    (lldb) po button.imageView
    

    After setting button's image, button.imageView assumed the size of the image, e.g. for a 320x240 image:

    (lldb) po button.imageView
    >
    

    It looks like button.imageView does not respect its content mode, but actually, it is the size of the button.imageView that is the problem.

    The answer is to set button's content alignment as well.

    The following sets button's image, sets button.imageView's content mode, and makes button.imageView fit the size of button:

    [button setImage:image forState:UIControlStateNormal];
    button.imageView.contentMode = UIViewContentModeScaleAspectFill;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
    

    Now, button.imageView is the same size as button, and has the desired content mode.

    (lldb) po button.imageView
    >
    

    The desired result is thereby achieved. Very handy!

提交回复
热议问题