I want to put images in UIScrollView. However, the problem is that when I try to put an image larger than UIScrollView, UIScrollView shows the upper part of images. I would like the scrollview to show the bottom part of the image. Right now, I have the following code:
let imgBot1 = UIImage(named:"Img1.jpg");
let imgBot2 = UIImage(named:"Img4.jpg");
let imgBot3 = UIImage(named:"Img5.jpg");
//Adding UIImage in UIImageView
let imgView1 = UIImageView(image:imgBot1)
let imgView2 = UIImageView(image:imgBot2)
let imgView3 = UIImageView(image:imgBot3)
//creating UIScrollView
let scrView2 = UIScrollView()
scrView2.frame = CGRectMake(0, self.view.frame.height/2,
self.view.frame.width, self.view.frame.height)
//content size of the scrollview
scrView2.contentSize = CGSizeMake(self.view.frame.width*3, self.view.frame.height)
//Size and place of UIImageView
imgView1.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
imgView2.frame = CGRectMake(width, 0, self.view.frame.width, self.view.frame.height)
imgView3.frame = CGRectMake(width*2, 0, self.view.frame.width, self.view.frame.height)
//adding the scrollview to the view
self.view.addSubview(scrView2)
scrView2.addSubview(imgView1)
scrView2.addSubview(imgView2)
scrView2.addSubview(imgView3)
scrView2.pagingEnabled = true
//Initial location of the scrollview
scrView2.contentOffset = CGPointMake(0, 0);
I would like to know how I can make the scrollview to show the bottom part of the image, and not the top part. Will you help me out?
I made this code, hope it will work for you. I used the storyboard, made a scrollView, added an imageView and added constrains to the image view to stick to the edges (don't know it that's necessary).
imageView = UIImage(named: "image")
scrollView.contentOffset = CGPoint(x: 0, y: image.image!.size.height)
Related
I see this topic in quite a few places but I can't figure out why exactly my code doesn't work.
I have an image of an artificial horizon that goes from -90 to 90 degrees. I want to view it through a small window which just shows around -20 to 20 degrees. Then I want to move the image up and down based on the angle my robot is leaning.
I started by adding a UIImage to a UIImageView. All of the alignment is correct. Then I thought the easiest way to move the image up and down was to add the UIImageView to a UIScrollView. Now I can't figure out how to get the alignment right. I see the image in there if I drag in the scrollview but as soon as I let go it goes back to where it was.
Here is the code I have. This is the first Swift code I have written so if there is a better way to do this I welcome any ridicule (just kidding, be gentle)
override func viewDidLoad() {
super.viewDidLoad()
let imageRect = CGRectMake(self.view.frame.width / 2 - 100, self.view.frame.height / 2, 200, 200)
self.myImageView = UIImageView.init()
self.myImageView = UIImageView(frame: imageRect)
self.myImageView.contentMode = UIViewContentMode.Center
self.myImageView.clipsToBounds = true
self.myImageView.image = UIImage.init(named:"horizon")
//self.view.addSubview(self.image)
self.myScrollView = UIScrollView(frame: imageRect)
self.myScrollView.contentSize = CGSize(width: imageRect.width, height: imageRect.height)
self.myImageView.center = self.myScrollView.center
self.myScrollView.frame = imageRect
self.myScrollView.backgroundColor = UIColor.blackColor()
self.myScrollView.contentOffset = CGPoint(x: 0, y: 0)
self.myScrollView.addSubview(self.myImageView)
self.view.addSubview(self.myScrollView)
/////////
self.connectionStatusLabel.text = "Disconnected"
self.connectionStatusLabel.textColor = UIColor.redColor()
self.textBox.font = UIFont(name: self.textBox.font!.fontName, size: 8)
// Watch Bluetooth connection
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.connectionChanged(_:)), name: BLEServiceChangedStatusNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.dataReceived(_:)), name: BLEDataChangedStatusNotification, object: nil)
// Start the Bluetooth discovery process
btDiscoverySharedInstance
}
You have to set the scrollView's contentSize to the actual image size not the imageView's size. And set the imageView's size to the actual image size as well:
let image = UIImage.init(named:"horizon")
// Set the imageView's size to the actual image size
self.myImageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
...
...
// Set the scrollView's contentSize to the actual image size
self.myScrollView.contentSize = image.size
I have an issue, I'm creating an imageView programmatically and then add it to a center view, which is kind of working. But the problem is that is not taking the whole space in the center view, it appears yes in the uiview but not covering all always a bit down. Any help?
The code:
//let backgroundImage = UIImageView(frame: centerView.frame)
let backgroundImage: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.centerView.bounds.size.width, height: self.centerView.bounds.size.height))
print("backgorundImage coordinates: \(backgroundImage.frame)")
backgroundImage.image = drawOverImage
backgroundImage.sizeThatFits(CGSizeMake(centerView.bounds.width, self.centerView.bounds.height))
//check this the image is being drawn bottom because is the fame for the previous 0.0
//backgroundImage.autoPinEdgeToSuperviewMargin(ALEdge.Top, relation: NSLayoutRelation.Equal)
//backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill //too big
//backgroundImage.contentMode = UIViewContentMode.ScaleAspectFit //sama
backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill
backgroundImage.clipsToBounds = true
//imageView.image = background
backgroundImage.center = view.center
let coordinatesForImage: CGRect = self.view.convertRect(backgroundImage.frame, toView: centerView)
let pointOfImage: CGPoint = backgroundImage.convertPoint(self.centerView.frame.origin, toView: backgroundImage)
print("coordinates test: \(coordinatesForImage)")
print("point x: \(pointOfImage.x)")
print("point y: \(pointOfImage.y)")
//backgroundImage.contentMode = UIViewContentMode.ScaleToFill
self.centerView.insertSubview(backgroundImage, atIndex: 0)
let pointOfImageToSuperView: CGPoint = (backgroundImage.superview?.convertPoint(backgroundImage.center, toView: self.centerView))!
print("superview imagepoint: \(pointOfImageToSuperView)")
The comments are all the thing I'm trying to do.
EDIT:
This is what is happening.
I missing a little bit from the bottom, now I don't know if is the size of the image or what, could i change the size of the uiview to match the image?
Simply try:
let backgroundImage: UIImageView = UIImageView(frame: self.centerView.bounds)
backgroundImage.clipsToBounds = true
backgroundImage.contentMode = .ScaleAspectFill
self.centerView.addSubview(backgroundImage)
Problem visually:
I have tried putting the image in the center of its own frame with no luck. I have also tried to center it with playing the x of the CGRect with no luck either. I presume I can just put an empty icon with the same background as the navigation bar; however, I don't want to do it that way. I might have 2-3 icons on the right; then what?
let image = UIImage(named: "some_logo")!
let imageSize = CGSizeMake(60, 42)
let marginX: CGFloat = (self.navigationController!.navigationBar.frame.size.width / 2) - (imageSize.width / 2)
let imageView = UIImageView(frame: CGRect(x: marginX, y: 0, width: imageSize.width, height: imageSize.height))
imageView.image = image
imageView.contentMode = .ScaleAspectFit
self.navigationItem.titleView = imageView
I prefer swift but obj-c solutions are welcomed as well.
Any pointers appreciated.
This app has nothing to do with KIA, it is just some logo I got off the google search, searching "some logo".
I have faced the same issue. Then i tried one code shown below.
override func viewDidAppear(animated: Bool) {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 40))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "googlePlus")
imageView.image = image
navigationItem.titleView = imageView
}
This Code working fine when i tested with Left & Right Bar Button.
But in my previous code there is no Right Bar Button.
So the image is moving towards right.
For solving this i created a Right Bar Button & change the Tint color to clear color.
So everything seems to be working fine. This is one Temporary Solution for your problem.
The easiest way of doing this is in Interface Builder.
Simply drag a 'NavigationItem' from the object library and place it into your ViewController, then place a UIView where the title goes (ensure you set the background to 'clear')
Then place a UIImageView into that view and set the image in the Attributes Inspector to your required image. Scale your UIImage accordingly and set your your constraints accordingly.
I created an extension for solving this problem using the hint of #idrougge.
In order to center the title view image no matter what buttons you have, a content view is set as title view, then the image view is added as child of the content view. Finally, using constraints the image view is aligned inside its parent (content view).
import UIKit
extension UIViewController {
func addLogoToNavigationBarItem() {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: <your_height>).isActive = true
imageView.contentMode = .scaleAspectFit
imageView.image = <your_image>
//imageView.backgroundColor = .lightGray
// In order to center the title view image no matter what buttons there are, do not set the
// image view as title view, because it doesn't work. If there is only one button, the image
// will not be aligned. Instead, a content view is set as title view, then the image view is
// added as child of the content view. Finally, using constraints the image view is aligned
// inside its parent.
let contentView = UIView()
self.navigationItem.titleView = contentView
self.navigationItem.titleView?.addSubview(imageView)
imageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
}
}
I hope this helps someone,
Xavi
As question heading stated "Swift / Obj-C" so I am sharing code of Obj-C :
UIImageView *titleImage = (UIImageView *)self.navigationItem.titleView;
titleImage = [[UIImageView alloc]initWithFrame:CGRectMake((self.navigationController.navigationBar.frame.size.width/2) - (100/2), 0, 100,self.navigationController.navigationBar.frame.size.height)];
//setting the image for UIImageView
titleImage.image = [UIImage imageNamed:#"someLogo"];
titleImage.contentMode = UIViewContentModeCenter;
self.navigationItem.titleView = titleImage;
Had same issue on phones with smaller sizes. Image in title was moving to right. Causing this issue back button -> [back_button][title_view]. Its centered when there is no back button or there is right bar button. Richard Hope's was right, you just need to put UIView first, and then put UIImageView as subview. Programmatically could be done like this.
private var imageView: UIView {
let bannerWidth = navigationBar.frame.size.width * 0.5 // 0.5 its multiplier to get correct image width
let bannerHeight = navigationBar.frame.size.height
let view = UIView()
view.backgroundColor = .clear
view.frame = CGRect(x: 0, y: 0, width: bannerWidth, height: bannerHeight)
let image = UIImage(named: "your_image_name")
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
view.addSubview(imageView)
return view
}
The just change titleView
navigationItem.titleView = imageView
What about setting the center of your image equals to the navigationBar.center instead of setting a margin?
//assuming we already have our navigationController
let myNicelLogoWidth = 100
let myNiceLogoHeight = 50
//start positioning your logo at 0.0, 0.0
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: myNicelLogoWidth, height: myNiceLogoHeight))
imageView.contentMode = .scaleAspectFit
imageView.center = navigationBar.center //the put your image at the center
let image = UIImage(named: "myNiceLogoImage")
imageView.image = image
navigationItem.titleView = imageView
I once face with this problem, and finally i found out that the problem is the previous navigation bar title still located next to burger button, but it's invisible.
Fast solution but not sure if it's the best is to change the previous navigation bar title to empty string before show the next view controller.
Hope it's help.
I can set an image to my TableView background, but the image is in the center of the view.
How can I set the image to top ?
I'm using staticTableView
let image = UIImageView(image: UIImage(named: "img.jpg"))
self.settingsTableView.backgroundView = image
self.settingsTableView.backgroundView?.frame = CGRectZero
self.settingsTableView.backgroundView?.contentMode = UIViewContentMode.ScaleAspectFit
If you're using a static table and theres no chance of changing it you might want to take an approach like this:
override func viewDidLoad() {
super.viewDidLoad()
//Create the UIImage
let image = UIImage(named: "testing")
//Create a container view that will take all of the tableView space and contain the imageView on top
let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.bounds.width, height: self.view.bounds.height))
//Create the UIImageView that will be on top of our table
let imageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.bounds.width, height: image!.size.height))
//Set the image
imageView.image = image
//Clips to bounds so the image doesnt go over the image size
imageView.clipsToBounds = true
//Scale aspect fill so the image doesn't break the aspect ratio to fill in the header (it will zoom)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
containerView.addSubview(imageView)
self.tableView.backgroundView = containerView
}
Make the cells or the headers transparent as you wish. I don't know how your UI should work. This method WON'T scroll the imageView but you can simply do it in the scrollView delegate method. Let me know if you need it to scroll and I'll help you out
I have a UIImageView with a perfectly working attached UITapGestureRecognizer. That's not where the problem is, but I'm adding the code snippet which adds the gesture to give more context:
let tapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: Selector("didTapImageView:")
)
imageView.addGestureRecognizer(tapGestureRecognizer)
imageView.userInteractionEnabled = true
This is the issue: the ImageView is inside a ScrollView that is resized depending on the device. The resize also works as expected, but when it happens, the UIImageView does not recognize the tap gesture anymore. Everything gets perfectly displayed, but tapping on the image does not trigger the didTapImageView method. Only if the scroll view is rezised.
The resizing of the UIScrollView happens inside a imagePickerController(picker, didFinishPickingMediaWithInfo) delegate method. Here it is:
let currentViewHeight = scrollView.frame.size.height
if currentViewHeight < heightLimit {
let frameRect = CGRect(x: 0, y: 0, width: self.view.frame.width, height: currentViewHeight + offset)
let frameSize = CGSize(width: scrollView.frame.size.width, height: currentViewHeight + offset)
scrollView.frame = frameRect
scrollView.contentSize = frameSize
}
How can I prevent the gesture recognizer from getting cancelled?