Set contentMode of UIImageView - ios

In Obj-C
imageView.contentMode = UIViewContentModeScaleAspectFill;
would set the contentMode.
Why does
imageView.contentMode = UIViewContentModeScaleAspectFill
not work in Swift?

Somewhat confusingly, Swift drops the prefix for ObjC enum values:
imageView.contentMode = .scaleAspectFill
This is because Swift already knows what enum type is being used. Alternatively, you can specify the enum too:
imageView.contentMode = UIViewContentMode.scaleAspectFill
Note: In versions of Swift before version 3, "scaleAspectFill" will need to be capitalized.

In swift language we can set content mode of UIImage view like
var newImgThumb : UIImageView
newImgThumb = UIImageView(frame:CGRectMake(0, 0, 100, 70))
newImgThumb.contentMode = .ScaleAspectFit

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
Select the ImageView (or any other control that has an embedded
imageView)
Check the base type of the attribute you want to set (in the case of contentMode this is UIViewContentMode)* see NB for how to...
Note the type of valid values that can be assigned to the base type (in this
case contentMode values correspond to a number)
Go to the attributes inspector and see the User Defined Runtime Attributes (see image)
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

In Swift 4 it is
imageView.contentMode = UIView.ContentMode.scaleAspectFit

In Swift Language we can set imageView in textField as given below.
let RightImageView = UIImageView()
RightImageView.image = image
let RightView = UIView()
RightView.addSubview(RightImageView)
RightView.frame = CGRectMake(0, 0, 30,30)
Give color to view & imageView So that you can check your added imageView position in textField
RightView.backgroundColor = UIColor.redColor()
RightImageView.backgroundColor = UIColor.blueColor()
RightImageView.contentMode = UIViewContentMode.ScaleAspectFill
RightImageView.frame = CGRectMake(0, 0,30,30)
textFieldForCountry.rightView = RightView

Related

SF Symbol imageView does not conform to pointSize?

I have an empty UIImageView in my storyboard, and have the outlet in my ViewController.swift file. In viewDidLoad, I'm calling the below code:
let config = UIImage.SymbolConfiguration(pointSize: 50, weight: .light)
self.symbol.image = UIImage(systemName: "calendar")
self.symbol.preferredSymbolConfiguration = config
The symbol loads fine, and even the weight is correctly reflected.
However, the size of the symbol image is still tied to the size of the UIImageView in the storyboard even though I have no constraints set on the UIImageView. And from what I can tell the pointSize declared in SymbolConfiguration has no effect on the size of the symbol image.
From what I can tell it seems that there are two ways to get pointSize in SF Symbols to work: 1. Do all of it programmatically or 2. do all of it in Storyboard / Inspector.
Does anyone know what I'm doing wrong or does SF Symbols not support Storyboard + code configuration?
I solved the problem by changing the contentMode property of the UIImageView object to .center.
let imageView = UIImageView()
imageView.contentModel = .center // This is the key step.
imageView.preferredSymbolConfiguration = .init(pointSize: 10)
iconView.image = UIImage(systemName: "name")
I figured it out, you have to call sizeToFit() after setting the configuration. I'm guessing Apple left it for the dev to call it so that they could prevent unnecessary recalculation of UI sizing thus potentially improving efficiency.
Anyway, the solution is: call sizeToFit() on the UIImageView after setting the configuration.
Try this way instead:
let config = UIImage.SymbolConfiguration(pointSize: 50, weight: .light)
self.symbol.image = UIImage(systemName: "calendar", withConfiguration: config)

In Swift, how to reuse a property in a UIVIewController

The question is very simple and I bet lots of you guys may had this situation.
I just have a property name called "carrotImage" like a ">" symbol as a property and want to place 2 times in my UIViewController by using view.addSubview. I don't actually want to create another new property which has exactly the same image as ">", but I'm thinking that if I really do view.addSubview(carrotImage) 2 times but in different places, and apply SnapKit or built-in autolayouts on them respectively, it would affect the other one.
As you can see the image:
There are 2 '>' and I really don't want to create 2 exactly same thing. is there a good way to do it without repeating? Thanks.
Here is my carrotImage property:
var carrotImage: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(systemName: "arrowtriangle.right.fill")
imageView.tintColor = .lightGray
return imageView
}()
For your use case, you do have to have 2 separate UIImageViews. However, they have the same image and properties, so you can reuse the code. If you do not need to later reference carrotImage, you can just make it computed variable like this (remove = and ()):
var carrotImage: UIImageView {
let imageView = UIImageView()
imageView.image = UIImage(systemName: "arrowtriangle.right.fill")
imageView.tintColor = .lightGray
return imageView
}
This way you can reuse the same code to create new UIImageView with arrowtriangle.right.fill where you need.

Customize Text Field

Hi I want to build some thing that look like the picture !
my problem is that text field can't be two section and use tiny pictures in it just like a picture
I want to make some thing just like the picture even the green part in the right of the each text field
here is what I want to do
Make a custom view and add it as
textField.rightViewMode = .always
// Set rightview mode
var rightImageView = UIImageView(image: UIImage(named: "image_icon"))
textField.rightView = rightImageView// Set right view as image view }
//textField Its your textfield object , Change it with your own
Try like this

Keep aspect ratio for UIbuttons background image

I've been looking for hours and all I find is old answers saying that it cannot be done.
I have a button where I'd like the background image to be as large as it can be, while keeping its aspect ratio. The background image keeps getting streched no matter what I do. I've tried.
var bluecircle = #imageLiteral(resourceName: "BLUE.png")
monBreak.contentMode = UIViewContentMode.scaleAspectFit
monBreak.setBackgroundImage(bluecircle, for: UIControlState.normal)
Do I really need to make an imageview and put an invisible button over it? That seems like welcoming A LOT of new things that could go wrong.
I tried
#IBOutlet weak var monBreak: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
var bluecircle = #imageLiteral(resourceName: "BLUE.png")
let theimagebehindmonBreak = UIImageView(image: bluecircle)
theimagebehindmonBreak.frame = CGRectFromString( "{{0,0},{40,40}}")
monBreak.contentMode = UIViewContentMode.scaleAspectFit
monBreak.addSubview(theimagebehindmonBreak)
theimagebehindmonBreak.image=bluecircle
theimagebehindmonBreak.contentMode = UIViewContentMode.scaleAspectFit
This gets the aspect ratio right, but since I want the layout to be dynamic setting its size to fixed values won't work, plus it's not centered.
At first I tired simply applying the constraints of the button like so
var dacontraints = NSLayoutConstraint(monBreak.constraints)
But at this point I get the error "Cannot invoke initializer for type 'NSLayoutConstraint' with an argument list of type '{[NSLayoutconstraints]}'
This is killing me
Sounds like a solution where subclassing fits.
Subclass UIButton, add an ImageView in the init, size it to the frame, and set the contentMode properly.
Old question but since I was looking for the same I think this is still valid.
I was trying to do the same (as everyone says) for backgroundImage it is impossible. However, if your button will consist of only an icon, then first you should be using the setImage method AND if you are using it you'll have access to the imageView property of the button. Since this is an UIImageView you can set the contentMode to whatever you like.

How add background image to UIControl

I create 3rd party keyboard and i try add background to my keys. I use UIControl for my keys, without storyboard.
I have several types of buttons and try to add background UIView for my characters.
let img = UIImage(named:"KeyBackground")
var bgImage: UIImageView?
bgImage = UIImageView(image: img)
bgImage!.frame = keyboardKey.frame
keyboardKey.addSubview(bgImage!)
keyboardKey.sendSubviewToBack(bgImage!)
keyboardKey.backgroundColor = UIColor.clearColor()
But is don't work.
I try to add background image like this:
keyboardKey.backgroundColor = UIColor(patternImage: UIImage(named:"KeyBackground")!)
But is looks bad...
What am i doing wrong?
The background looks like that because the size of your image is a little smaller than the size of each key, and the image is being tiled (repeated to fill the space - so each key contains the background image and pieces of the surrounding tiles to the right, bottom, and bottom-right).
The UIColor(patternImage:) docs say that
During drawing, the image in the pattern color is tiled as necessary to cover the given area.
Your first solution probably didn't work because you inserted your UIImageView as the bottom-most subview - I assume another (opaque) view was on top of it. What type of UIControl are you using? UIButton, for example, already provides some "background image" support out of the box.
Oh, it's so easy. My keyboardKey.frame, at the time of the call this method, have frame = 0, 0, 0, 0.
Night a bad time for work:)

Resources