UIButton doesn't listen to content mode setting?

后端 未结 16 2127
情话喂你
情话喂你 2020-12-02 08:45

firstButton is a UIButton of type Custom. I\'m programmatically putting three of them across each cell of a table, thusly:

[firstButton setImage:markImage fo         


        
16条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 09:16

    Rather than setting the contentMode on the button itself, you'll want to set contentHorizontalAlignment and contentVerticalAlignment properties and (crucially) the contentMode for the button's imageView for any kind of aspect fill or fit. Here's an example:

    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
    button.imageView.contentMode = UIViewContentModeScaleAspectFit;
    

    Of course, you can also do other things like aligning the button's image to the top of the button. If you don't need an aspect fill or fit, you just can set the alignment by itself:

    button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
    

    In Swift, you'll want to use:

    button.contentHorizontalAlignment = .fill
    button.contentVerticalAlignment = .fill
    button.imageView?.contentMode = .scaleAspectFit
    

    This works for all versions of iOS, including the latest versions with auto-layout, (i.e. iOS 4 up to iOS 11+).

提交回复
热议问题