I have been just learning Swift language and I am pretty new at this.
I am trying to create a table view with protoype cell containing a ImageView. I want "ImageView" make centered according to x Axis with "main storyoard". At first glance, everything is good until I open the simulator. After opening the simualator, I see that it was absoulutely not centered on x-axis. (I am sure that my simulator’s phone type and my storyboard’s phone type is true.)
Here, I want to center the imageView with code. But I can’t figure out where I should put the code.
I am trying to put this code if it is available. (I guess it should be.) If you have any suggestion to just relocate the x-axis of the imageview, I am totally open.
let width = view.frame.size.width
var frm: CGRect = imageView!.frame
frm.origin.x = (width/2) - (frm.midX/2)
frm.origin.y = frm.origin.y
frm.size.width = frm.size.width
frm.size.height = frm.size.height
cell.imageView!.frame = frm
In order to put the code, I am 2 class types: "UITableViewCell" and "UIViewController" Which one and how should I put the code?
How should align the imageView inside of the that tableView?
I added all unfinished project to this link. This is not a serious project. Just a project serving to learners.
https://github.com/mmtbey/SwiftFirebase_InstaClone
To sign in:
username: [email protected]
password: 123456
Thank you.
Note: I can align the frame of imageView on storyboard easily. However, centering on x-axis doesn’t work in deed. When I run the simulator, I see the image left-aligned. I can fix the situation by inreasing the gap between left line and imageView. But that is not a proper way in order to solve the problem.
2
Answers
I guess there is a bug here and I could not find a way to fix the situation. However, I deleted all constraits inside of the viewController and I coded the constraints like below.
Have a nice day.
Since you are using auto layout, I don’t think you should try to fix it using frames.
Fixing it with auto layout is what I recommend.
Looking at your Storyboard image, it does not seem like you are setting the
centerX
andcenterY
constraints.Here is how you do it:
On doing that, things should center properly: