Set contentMode of UIImageView

后端 未结 5 1181
清歌不尽
清歌不尽 2020-12-15 16:36

In Obj-C

imageView.contentMode = UIViewContentModeScaleAspectFill;

would set the contentMode.

Why does

imageView.contentM

5条回答
  •  星月不相逢
    2020-12-15 17:30

    tldr;

    See the code answer for Swift 3 at the bottom.

    Note - Please comment if more information is needed.

    Please checkout the longer answer below which includes how to use the solution for setting all other properties within your Storyboard or Xib/Nib file.

    There's nothing wrong with the other answers but I want to share how setting values on objects can be done in Interface Builder. I know the OP is asking for code, this example is just being shared for completeness. Of course if one wanted to animate property changes or needed the code versions then the other answers continue to apply.

    Within Interface Builder

    1. Select the ImageView (or any other control that has an embedded imageView)
    2. Check the base type of the attribute you want to set (in the case of contentMode this is UIViewContentMode)* see NB for how to...
    3. Note the type of valid values that can be assigned to the base type (in this case contentMode values correspond to a number)
    4. Go to the attributes inspector and see the User Defined Runtime Attributes (see image)
    5. Add a user defined attribute of type Number and the property name that you want to set (in this case it would be contentMode)

    NB - An easy way to explore the underlying types of properties is to Cmd+Click on the property in your source code editor, then Cmd+Click on the type for that property.

    Here is a simple example where I set some properties for a UIButton, which includes a UIImageView as one of its subviews. The example shows how one can set properties on the top object (UIButton) and the sub object (UIImageView).

    If you have an imageView selected then just set the User Defined Runtime Attribute to contentMode of type Number and whatever value you want. This is a good method because it will work for both Objc and Swift.

    What's great is that you can use the same method to capture many other static property values for anything that appears within Interface Builder.

    Documented values for the UIViewContentMode enum

    BTW - Swift 3 changes the enum values to begin with a lower case so the following would work in Swift 3:

    imageView.contentMode = .scaleAspectFill
    

提交回复
热议问题