I'm trying to make a line graph drawn using a CGRect scrollable by the user. I've set its container view to be scrollable (i want a horizontal scroll so the line can extend past the screen), but it doesn't appear to be having any effect. Here's the code in my actual view controller:
#IBOutlet weak var containerView: UIScrollView!
#IBOutlet weak var graphView: GraphView!
override func viewDidLoad() {
super.viewDidLoad()
logWeightButton.enabled = false
logWeightField.delegate = self
logWeightField.keyboardType = .NumberPad
self.view.addSubview(containerView)
containerView.addSubview(graphView)
containerView.contentSize = graphView.rectDisplay.size
pageLoad()
}
and here's the code declaring the CGRect(within a UIView class)
override func drawRect(rect: CGRect) {
if dataPoints.count == 0 {
return
} else {
self.drawLine(dataPoints, rect: rect, xCoordinates: nil, color: UIColor.blackColor())
if xCoordinates.count != 0 {
self.drawLine(actualPoints, rect: rect, xCoordinates: xCoordinates, color: UIColor.redColor())
}
rectDisplay = rect
}
}
Figured out that I needed to turn off auto-layout in the storyboard file inspector - if it's not disabled, it can overwrite scroll views.
I also made sure to enable scroll with
containerView.scrollEnabled = true
and set the containerView frame to
self.view.frame
I don't have enough reputation to post an image, so here it is:
http://i.stack.imgur.com/ZOBJp.png
The graph now scrolls, but my whole display is a mess (I believe because of setting the container frame to the size of the view), so the cycle continues.
FINAL UPDATE:
Learned that the frame of the scroll view has to be smaller than its content for it to scroll (which is why setting it to the view frame worked - the width of the view was less than the width of the line graph), so I set my frame to
containerView.frame = CGRect(x: 43.0, y: 147.0, width: 300.0, height: 117.0)
And everything works now. Hope this is helpful for someone else!
Related
I can't believe something this easy when I did not use auto-layout is this hard with auto-layout. I put everything in a contentView so that it's a simultaneous zoom for both views (ImageView and UIView). The UIView for drawing should be the same size as the UIImageView and not bigger. I have this hierarchy at the moment.
UIScrollView
- ContentView
-- UIView (For drawing eg, drawView)
-- UIImage (For showing a background image to draw on)
The drawView is a view on top of the imageView, the problem now is as following:
Users can draw out of bounds of the UIImageView. This should only be possible drawing on the imageView.
Drawings are under the UIImageView, while the drawView is on top.
Code:
var afbeelding: UIImage?
#IBOutlet var imageView: UIImageView!
#IBOutlet var drawView: DrawingCanvas!
#IBOutlet var contentView: UIView!
var dag: Dag?
#IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
drawView.dag = dag
if let afbeelding = afbeelding {
imageView.image = afbeelding
}
scrollView.panGestureRecognizer.minimumNumberOfTouches = 2
scrollView.panGestureRecognizer.maximumNumberOfTouches = 2
scrollView.minimumZoomScale = 0.2;
scrollView.zoomScale = 1.0;
scrollView.maximumZoomScale = 5.0
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return contentView
}
Images:
Could anyone steer me in the right direction?
I'm not very familiar with Interface Builder but for your layer order problem I'd try swapping them; perhaps the order in which they're shown is the order in which they're added.
As for drawing outside the bounds, you'd need to look at the documentation for DrawingCanvas but perhaps its clipsToBounds property will work?
Users can draw out of bounds of the UIImageView. This should only be possible drawing on the imageView.
It seems like your image view has its contentMode set to .scaleAspectFit, but has all 4 sides pinned to the superview. This means that the image view spans the entire contentView, but the image itself is smaller.
I think the easiest way around this is to get the frame of the actual image using AVMakeRect(aspectRatio:insideRect:), then adjusting drawView's frame.
let rect = AVMakeRect(aspectRatio: image.size, insideRect: imageView.frame)
/**
Instead of constraining `drawView`'s edges, use x, y, width, and height.
This makes setting them easier.
You'll need to connect your constraints via an #IBOutlet (see https://stackoverflow.com/a/40584432/14351818)
*/
drawViewLeftConstraint.constant = rect.origin.x
drawViewTopConstraint.constant = rect.origin.y
drawViewWidthConstraint.constant = rect.width
drawViewHeightConstraint.constant = rect.height
Drawings are under the UIImageView, while the drawView is on top.
Actually, the image view is on top. The order is lowest -> highest, so just switch them.
I would like to have a horizontal scroll layout which displays images. It works fine if setup 0, 0, 0 and 0 the constraints of the UIScrollView. The problem is exactly when I change the constraints to make margins surrounded the UIScrollView. This is what happens:
First image in the UIScrollView
Second image in the UIScrollView
Third image in the UIScrollView
As you can see, each time you scroll, more off-center the current page is.
I have tried to subtract trailing and leading constrains constants to the width of the scrollLayout, play with frames and bouds but without success.
If I run this example in a smaller display like iphone 5S, the problem is more pointed.
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var pageController: UIPageControl!
#IBOutlet weak var scrollView: UIScrollView!
let imagesArray = ["b_1", "b_2", "b_3", "b_4", "b_5"]
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.isPagingEnabled = true
self.pageController.numberOfPages = imagesArray.count
self.pageController.pageIndicatorTintColor = UIColor.blue
self.pageController.currentPageIndicatorTintColor = UIColor.gray
for i in 0...imagesArray.count - 1{
let imageView = UIImageView()
imageView.contentMode = .scaleToFill
imageView.image = UIImage(named: self.imagesArray[i])
let xPos = CGFloat(i)*self.view.bounds.size.width
imageView.frame = CGRect(x: xPos, y: 0, width: view.frame.size.width, height: self.scrollView.frame.size.height )
self.scrollView.contentSize.width = view.frame.size.width*CGFloat(i+1)
self.scrollView.addSubview(imageView)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = scrollView.contentOffset.x/scrollView.frame.width
self.pageController.currentPage = Int(page)
}
}
So, I would like to know how to always obtain the current image centered.
Thank you
EDITED with Rajesh results and view debug:
I would recommend using a UICollectionView in place of a UIScrollView - otherwise you will be building a lot of the basics from scratch. You can use a collection view that centers the images, make sure paging is enabled and you should get the interface you're looking for. Make sure to adopt / conform to the UICollectionViewDelegate & UICollectionViewDelegateFlowLayout protocols with your view controller & set those delegates on your collection view. Hope that helps! Best of luck.
I have a UICollectionViewController embedded inside a UINavigationController which in turn embedded inside a UITabBarController.
I want to add a UIView to the UICollectionViewController just above the tab bar (shown by red rectangle).
I have the UIView created separately as a nib file.
import UIKit
class BottomView: UIView {
#IBOutlet var view: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
fileprivate func commonInit() {
Bundle.main.loadNibNamed("BottomView", owner: self, options: nil)
view.frame = self.frame
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
addSubview(view)
}
}
And I initialize and add it in the UICollectionViewController like so.
class CollectionViewController: UICollectionViewController {
fileprivate var bottomView: BottomView!
override func viewDidLoad() {
super.viewDidLoad()
let yPos = view.bounds.height - (tabBarController!.tabBar.frame.size.height + 44)
bottomView = BottomView(frame: CGRect(x: 0, y: yPos, width: view.bounds.width, height: 44))
collectionView?.addSubview(bottomView)
}
// ...
}
I figured if I substract the combined height of the bottom view plus the tab bar from the entire view's height, I should be able to get the correct y position value. But it's not happening. The view is getting added but way off screen.
How do I calculate the correct y position without hardcoding it?
Example demo project
I would suggest adding the BottomView to the UICollectionViewController's view rather than to the collection view itself. This is part of the problem you're having.
You're also trying to set the frame of the BottomView in the viewDidLoad() method using values from view.bounds. The CGRect will return (0.0, 0.0, 0.0, 0.0) at this point because the layout has yet to take place, which is most likely why your positioning is off. Try moving your layout logic to the viewWillLayoutSubviews() method and see if that helps.
A better approach would be by setting auto layout constrains rather than defining a frame manually, this will take a lot of the leg work out for you.
Here's a quick example:
self.bottomView.translatesAutoresizingMaskIntoConstraints = false
self.view.insertSubview(self.bottomView, at: 0)
self.bottomView.bottomAnchor.constraint(equalTo: self.view.layoutMarginsGuide.bottomAnchor).isActive = true
self.bottomView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
self.bottomView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
self.bottomView.heightAnchor.constraint(equalToConstant: 100.0).isActive = true
You can apply autolayout logic in your viewDidLoad() and it should work correctly.
You can find some more information on setting autolayout constraints programatically here:
https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html
Sounds what you want to achieve is exactly the footer view for the UICollectionView.
A footerView is like a view that will stick to the bottom of the collectionView and wont move with the cells.
This will help you add a footer View: https://stackoverflow.com/a/26893334/3165112
Hope that helps!
I am adding my intro screens in a scrollview.So I have to scroll horizontally only.I have set constraints for scrollview(top, bottom.leading, trailing).I have added subviews like the following
for i in 0..<self.arrIntro.count{
let view = IntroScreenView.instanceFromNib()
let x = CGFloat(i) * self.scrollIntro.frame.size.width
view.frame = CGRect(x: x, y: 0, width: self.scrollIntro.frame.size.width, height: self.scrollIntro.frame.size.height)
print(view,self.scrollIntro)
view.imgIntro.image = UIImage(named: "image-1")//UIImage(contentsOfFile: self.arrIntro[i]["Link"] as! String)
print(self.arrIntro[i]["Link"] as! String)
self.scrollIntro.addSubview(view)
}
self.scrollIntro.contentSize = CGSize(width: (CGFloat(self.arrIntro.count) * self.scrollIntro.frame.size.width ) , height: self.scrollIntro.frame.size.height)
but my scrollview is vertically scrolling little bit.How should I avoid this.Any autolayout issue?
You're not adding any constraints to your views. Add height and width constraints to each item, constraints between the views and constraints from the views to the scroll view. Note that the constraints between the Su views and the scroll view will set the content size for you.
Scroll view scrolls vertically, when contentSize.height is greater than the scrollView height.
Just make sure, your contentSize.height is not greater than the scrollView.frame.size.height.
One reason, that I could guess is that, you might be setting contentSize a point after which the frames of the scroll view changes. You should move setting you contentSize in viewDidLayoutSubviews()
Sample : This code makes vertical scroll
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize = CGSize(width: self.scrollView.bounds.width*5, height: self.scrollView.frame.height)
}
}
And this does not
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet var scrollView: UIScrollView!
override func viewDidLayoutSubviews() {
scrollView.contentSize = CGSize(width: self.scrollView.bounds.width*5, height: self.scrollView.frame.height)
}
}
I want to implement something similar to Instagram activity screen header:
I added two buttons for Following and You which are insides an UIView(header). For the bottom blue bar I added an UIView.
Where exactly should I animate that UIView bar to move from Following to You screen when switching pages inside UIPageViewController?
Or maybe there is a better solution to do this ?
For something like this, I like using property observers to keep the API nice and clean for calling code. In the following example I am doing just that and manually adjusting the frame values, but in practice you'll probably want to use Auto Layout and animate your constraints.
class MyHeader: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
#IBOutlet weak var selectionView: UIView!
var buttons = [UIButton]()
var selectedTabIndex: Int {
didSet {
UIView.animateWithDuration( 0.5) {
let targetButton = self.buttons[ self.selectedTabIndex ]
var frame = self.selectionView.frame
frame.origin.x = targetButton.frame.minX
frame.origin.y = targetButton.frame.maxY - frame.height
frame.size.width = targetButton.frame.minX
self.selectionView.frame = frame
}
}
}
}