Keep aspect ratio for UIbuttons background image - ios

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.

Related

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.

Why do my objects get placed and sized so perfectly when I add them to a UIKitView?

So I have the following UIKit elements I am adding to my UIViewController to control the simulation that appears. I expected to have to write a lot of placement code but instead everything appears perfectly no-mater what device... my question is why?
let menuButton = UIButton()
let statusLabel = UILabel()
let segmentedLabel = UISegmentedControl(items: ["None", "Glow", "Cloud"])
func initializeUI() {
//The menu button that opens up the options for the simulations
menuButton.layer.borderColor = UIColor.lightGray.cgColor
menuButton.layer.borderWidth = 1
menuButton.layer.cornerRadius = 5
menuButton.layer.backgroundColor = UIColor.darkGray.cgColor
menuButton.showsTouchWhenHighlighted = true
menuButton.imageView?.contentMode = UIViewContentMode.scaleAspectFit
menuButton.setImage(UIImage(named: "hamburger.png"), for: UIControlState.normal)
menuButton.addTarget(self, action: #selector(menuPress), for: UIControlEvents.touchDown)
view.addSubview(menuButton)
//Will display the status of the simulation
statusLabel.text = "Particle Simulation"
statusLabel.textColor = UIColor.darkGray
view.addSubview(statusLabel)
//Will display visual options
view.addSubview(segmentedLabel)
}
The size of each of the elements is perfect and they dont overlap. The label is in the bottom left corner the button is in the bottom right and the segmented view is in the top left corner (of my landscape app).
An additional question I have is if I wanted to start placing these objects programmatically how would I do so? The elements don't have an attribute position that I can work with and if I do something like menuButton.frame.size.height *= 20 that does not make the menu button super tall.
The reason this works is that all of your UI items in your example have an “intrinsic” content size so they are able to create their own frame. Add a standard UIView the same way and you will be out of luck. Also the views are creating their own constraints based on initial frames using Auto Resizing Masks(Also known as Springs and Struts).
Finally to place items you would set the frame directly. Just math. Good luck.
Super important to understand intrinsic content size. Some frame changes might require you to turn off automatic constraints but this is usually not the case but could be the problem with your button
UIView.translatesAutoresizingMaskIntoConstraints = false

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

UISegmentedControl maintain aspect ratio on image

I'm having a hard time making images on a UISegmentedControl keep their aspect ratio and not scale to all sides.
Here's what it looks like:
The images are 100X100(except nr 6 gonna replace soon) and I want them to maintain the aspect ratio.
I have tried:
self.segment.contentMode = .ScaleAspectFit
//and:
self.segment.contentMode = UIViewContentMode.Center
Are there a way I can target the UIImageView in the segment..that way I can set the contentMode..right? Or is there another approach?
Thanks
segmentedControl.subviews.flatMap{$0.subviews}.forEach { subview in
if let imageView = subview as? UIImageView, let image = imageView.image, image.size.width > 5 {
// The imageView which isn't separator
imageView.contentMode = .scaleAspectFit
}
}
Actually, there's a great, general purpose solution for this:
UIImageView.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).contentMode = .scaleAspectFit
This uses the approach described here: UIImageView.appearance is overriding UISegmentedControl.appearance
In my case, I constrained it to a subclass of UISegmentedControl (in case I want the default aspectFill for other situations).
I didn't find how to set the contentMode to ScaleAspectFit but you can use the following code to set a margin around your image when you are setting the image :
yourSegmentedControl.setImage(yourImage.resizableImage(withCapInsets: .init(top: 0, left: 10, bottom: 0, right: 10), resizingMode: .stretch), forSegmentAt: 0)
You can change the values of "top", "left", "bottom" and "right" as you want.
This worked for me, I hope it will help!
It is probably late for this, but Im sure it will help someone.
My Problem #1:
Images in the segmented control are distorted in ratio.
My Problem #2:
You can't even change the colour of the image. It remains black. Even if you use .alwaysTemplate and imageview tint colour. It wont budge.
Solution:
Forget trying to hack the SDK, or achieving the goal through unofficial means. Apple can easily change the SegmentedControl and all your work becomes redundant.
Use this instead: BetterSegmentedControl. Happy coding.
It is highly customisable and easy to use, plus it supports images.

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