Playground, unable to set same UIImageView to more than one UIView - swift

I've got this code
override public func viewDidLoad() {
let imageBlankCard = UIImage(named: "BlankCard.png")
let imageViewBlankCard = UIImageView(image: imageBlankCard)
rockCard.addSubview(imageViewBlankCard)
scissorCard.addSubview(imageViewBlankCard)
paperCard.addSubview(imageViewBlankCard)
self.view.addSubview(rockCard)
self.view.addSubview(scissorCard)
self.view.addSubview(paperCard)
}
But when I run the playground, only the latest UIView (paperCard) is displayed properly, the other cards are not shown at all as you can see in the image here: there should be two cards like the last one, in place of the arrows.
Can someone help me? Thanks everybody!

According to the documentation,
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
This explains the behaviour that you're getting.
One solution to this is to create three separate image views and add each of them as a subview.
Judging by the variable names, I think you are creating something similar to a rock paper scissors game. And you have three views that each holds an image view with the image of a blank card. And you want to add the image of a stone, paper and scissors as an overlay to the image view. If that's what you want to do, why not just make rockCard, paperCard and scissorsCard themselves UIImageViews and set the image to be BalnkCard.png?
let imageBlankCard = UIImage(named: "BlankCard.png")
rockCard.image = imageBlankCard
scissorsCard.image = imageBlankCard
paperCard.image = imageBlankCard

Related

Custom TabBarController with active circle

After reading a few articles about custom UITabBarControllers, I am left more confused than before I even started doing the research in the first place.
My goal is to create a custom TabBar with 3 important properties:
No text, just icons
The active icon is marked by a circle filled with a color behind it, and therefore needs a different icon color
Here's what I am trying to achieve:
I've been able to remove the text and center the icon by following another StackOverflow answer (Remove tab bar item text, show only image), although the solution seems like a hack to me.
How would I go about creating a circle behind the item and change the active item's color?
Also, would someone mind explaining the difference between the XCode inspector sections "Tab Bar Item" and "Bar Item", which appear directly under each other?
The first step is simple: leaving the title property of the UITabbarItem empty should hide the label.
Your second step can actually be broken down into two steps: changing the color of the icon and adding a circle behind it.
The first step here is simple again: you can set a different icon to use for the currently selected ViewController (I use Storyboards, this process is pretty straightforward). What you'd do is add a white version of the icon to be shown when that menu option is selected.
The final step is displaying the circle. To do this, we'll need the following information:
Which item is currently selected?
What is the position of the icon on the screen?
The first of these two is pretty easy to find out, but the second poses a problem: the icons in a UITabBar aren't spaced around the screen equally, so we can't just divide the width of the tabbar by the amount of items in it, and then take half of that to find the center of the icons. Instead, we will subclass UITabBarController.
Note: the tabBar property of a UITabBarController does have a .selectionIndicatorImage property. You can assign an image to this and it will be shown behind your icon. However, you can't easily control the placement of this image, and that is why we still resort to subclassing UITabBarController.
class CircledTabBarController: UITabBarController {
var circle: UIView?
override func viewDidLoad() {
super.viewDidLoad()
let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: (tabBar.frame.width / numberOfItems) - 20, height: tabBar.frame.height)
circle = UIView(frame: CGRect(x: 0, y: 0, width: tabBarItemSize.height, height: tabBarItemSize.height))
circle?.backgroundColor = .darkGray
circle?.layer.cornerRadius = circle!.frame.width/2
circle?.alpha = 0
tabBar.addSubview(circle!)
tabBar.sendSubview(toBack: circle!)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let index = -(tabBar.items?.index(of: tabBar.selectedItem!)?.distance(to: 0))!
let frame = frameForTabAtIndex(index: index)
circle?.center.x = frame.origin.x + frame.width/2
circle?.alpha = 1
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
let index = -(tabBar.items?.index(of: item)?.distance(to: 0))!
let frame = frameForTabAtIndex(index: index)
self.circle?.center.x = frame.origin.x + frame.width/2
}
func frameForTabAtIndex(index: Int) -> CGRect {
var frames = tabBar.subviews.compactMap { (view:UIView) -> CGRect? in
if let view = view as? UIControl {
for item in view.subviews {
if let image = item as? UIImageView {
return image.superview!.convert(image.frame, to: tabBar)
}
}
return view.frame
}
return nil
}
frames.sort { $0.origin.x < $1.origin.x }
if frames.count > index {
return frames[index]
}
return frames.last ?? CGRect.zero
}
}
Now use this subclass of UITabBarController instead of the base class.
So why this approach over simply changing the icon to a circled one? Because you can do many different things with this. I wrote an article about animating the UITabBarController in a similar manner, and if you like, you can easily use above implementation to add animation to yours too.
The easiest and actually cleanest way to do it is to design your icons and import them as images to the .xcassets folder. Then you can just set the different icons for the different states for each of the viewControllers with:
ViewController.tabBarItem = UITabBarItem(title: "", image: yourImage.withRenderingMode(.alwaysOriginal), selectedImage: yourImage)
your selected image will be the one with the circle and the image will be without. It is way easier than manipulating the images in xcode and it is also less expensive since the compiler only has to render the images and doesn't have to manipulate them.
About the other question UIBarItem is
An abstract superclass for items that can be added to a bar that appears at the bottom of the screen.
UITabBarItem is a subclass of UIBarItem to provide extra funtionality.

Swift shrink UIImageView according to what image it contains

I have an UIImageView which is as big as the whole view. When I insert an image, I would like for the image view to shrink itself in order for it to be as big as the image I insert itself. I cannot find a way to do it.
There are a number of ways you can approach this assuming you have a UIImageView declared like so:
#IBOutlet var dynamicImageView: UIImageView!
When changing your image, set the imageView size to that of the UIImage e.g:
func changeImage(){
if let image = UIImage(named: "Octocat"){
dynamicImageView.image = image
dynamicImageView.frame.size = image.size
print("Size Of ImageView = \(dynamicImageView.frame.size)")
}
}
Just use the .sizeToFit method e.g:
func changeImageAgain(){
if let image = UIImage(named: "Octocat"){
dynamicImageView.image = image
dynamicImageView.sizeToFit()
print("Size Of ImageView = \(dynamicImageView.frame.size)")
}
}
Running on an iPhone 7 Plus the UIImageView size is initially (375,647), and when applying either method the size changes to (800,665) which is the same size as the GitHub OctoCat:
I have created one demo app which will contains XIB with image view. Here I have written code to resize imageView as per image size. This code is working in my project, I shared link for demo app, you can download and test it.
In this project, I have implemented code to create imageView based on image size and vertically and horizontally centred aligned.
Also implemented code to zoom image.
https://app.box.com/s/sro2g7gdv5c67f9oj97gfhicjnpo2vqc
I hope this will work for you and as per your requirement.

Tracking the position of a NSCell on change

I have a NSTableView and want to track the position of its containing NSCells when the tableView got scrolled by the user.
I couldn’t find anything helpful. Would be great if someone can lead me into the right direction!
EDIT:
Thanks to #Ken Thomases and #Code Different, I just realized that I am using a view-based tableView, using tableView(_ tableView:viewFor tableColumn:row:), which returns a NSView.
However, that NSView is essentially a NSCell.
let cell = myTableView.make(withIdentifier: "customCell", owner: self) as! MyCustomTableCellView // NSTableCellView
So I really hope my initial question wasn’t misleading. I am still searching for a way how to track the position of the individual cells/views.
I set the behaviour of the NSScrollView (which contains the tableView) to Copy on Scroll in IB.
But when I check the x and y of the view/cells frame (within viewWillDraw of my MyCustomTableCellView subclass) it remains 0, 0.
NSScrollView doesn't use delegate. It uses the notification center to inform an observer that a change has taken place. The solution below assume vertical scrolling.
override func viewDidLoad() {
super.viewDidLoad()
// Observe the notification that the scroll view sends out whenever it finishes a scroll
let notificationName = NSNotification.Name.NSScrollViewDidLiveScroll
NotificationCenter.default.addObserver(self, selector: #selector(scrollViewDidScroll(_:)), name: notificationName, object: scrollView)
// Post an intial notification to so the user doesn't have to start scrolling to see the effect
scrollViewDidScroll(Notification(name: notificationName, object: scrollView, userInfo: nil))
}
// Whenever the scroll view finished scrolling, we will start coloring the rows
// based on how much they are visible in the scroll view. The idea is we will
// perform hit testing every n-pixel in the scroll view to see what table row
// lies there and change its color accordingly
func scrollViewDidScroll(_ notification: Notification) {
// The data's part of a table view begins with at the bottom of the table's header
let topEdge = tableView.headerView!.frame.height
let bottomEdge = scrollView.bounds.height
// We are going to do hit-testing every 10 pixel. For best efficiency, set
// the value to your typical row's height
let step = CGFloat(10.0)
for y in stride(from: topEdge, to: bottomEdge, by: step) {
let point = NSPoint(x: 10, y: y) // the point, in the coordinates of the scrollView
let hitPoint = scrollView.convert(point, to: tableView) // the same point, in the coordinates of the tableView
// The row that lies that the hitPoint
let row = tableView.row(at: hitPoint)
// If there is a row there
if row > -1 {
let rect = tableView.rect(ofRow: row) // the rect that contains row's view
let rowRect = tableView.convert(rect, to: scrollView) // the same rect, in the scrollView's coordinates system
let visibleRect = rowRect.intersection(scrollView.bounds) // the part of the row that visible from the scrollView
let visibility = visibleRect.height / rowRect.height // the percentage of the row that is visible
for column in 0..<tableView.numberOfColumns {
// Now iterate through every column in the row to change their color
if let cellView = tableView.view(atColumn: column, row: row, makeIfNecessary: true) as? NSTableCellView {
let color = cellView.textField?.textColor
// The rows in a typical text-only tableView is 17px tall
// It's hard to spot their grayness so we exaggerate the
// alpha component a bit here:
let alpha = visibility == 1 ? 1 : visibility / 3
cellView.textField?.textColor = color?.withAlphaComponent(alpha)
}
}
}
}
}
Result:
Update based on edited question:
First, just so you're aware, NSTableCellView is not an NSCell nor a subclass of it. When you are using a view-based table, you are not using NSCell for the cell views.
Also, a view's frame is always relative to the bounds of its immediate superview. It's not an absolute position. And the superview of the cell view is not the table view nor the scroll view. Cell views are inside of row views. That's why your cell view's origin is at 0, 0.
You could use NSTableView's frameOfCell(atColumn:row:) to determine where a given cell view is within the table view. I still don't think this is a good approach, though. Please see the last paragraph of my original answer, below:
Original answer:
Table views do not "contain" a bunch of NSCells as you seem to think. Also, NSCells do not have a position. The whole point of NSCell-based compound views is that they're much lighter-weight than an architecture that uses a separate object for each cell.
Usually, there's one NSCell for each table column. When the table view needs to draw the cells within a column, it configures that column's NSCell with the data for one cell and tells it to draw at that cell's position. Then, it configures that same NSCell with the data for the next cell and tells it to draw at the next position. Etc.
To do what you want, you could configure the scroll view to not copy on scroll. Then, the table view will be asked to draw everything whenever it is scrolled. Then, you would implement the tableView(_:willDisplayCell:for:row:) delegate method and apply the alpha value to the cells at the top and bottom edges of the scroll view.
But that's probably not a great approach.
I think you may have better luck by adding floating subviews to the scroll view that are partially transparent, with a gradient from fully opaque to fully transparent in the background color. So, instead of the cells fading out and letting the background show through, you put another view on top which only lets part of the cells show through.
I just solved the issue by myself.
Just set the contents view postsBoundsChangedNotifications to true and added an observer to NotificationCenter for NSViewBoundsDidChange. Works like a charm!

Swift - Is there an UIImageViewDelegate?

So I have been out of the iOS coding world for a bit and I am going through Swift at the moment.
In Objective-C I was able to change an image on the fly, but to do so I had to set the image delegate. The other reason I set the delegate was so I could hide the UIImageView
In Swift I seem to have an issue with this.
With the playground I can do this fine:
let responseImageView:UIImageView!
responseImageView.hidden = true
But in the project this does not work.
Can someone help me out here?
In my project I have this code :
#IBOutle var responseImageView: UIImageView!
//Inside a function I have this:
let smile = "smile.png"
imageName = UIImage(named: smile)!
responseImageView = UIImageView(image: imageName)
That code does not work.
And I can't hide the image by doing this:
responseImageView.hidden = true
If you created the actual UIImageView in the Storyboard or Interface Builder (and connected the IBOutlet correctly - it's always a good idea to double check this if something isn't working as expected!) you should not try to instantiate it again in code just to change the image. Instead, change the image by accessing the UIImageView's .image property, like so:
let smile = "smile.png"
let image = UIImage(named: smile)
responseImageView.image = image
Edit:
Just to clarify: by "instantiate" I specifically mean this line from you project code:
responseImageView = UIImageView(image: imageName)
Doing this in your function will break the connection you've set up in the storyboard. If you put a break point after that line or a println("\(responseImageView.superview)") you'll see that your instance of responseImageView is now no longer attached to a superview (explaining why you can change it's image or hide or unhide it all you want - you'll never see any change in the app).

Getting a UIView's visible rectangle

I have a UIScrollView that contains a custom UIView. Inside the custom UIView, I'd like to know the rectangle in which it's visible (i.e. not clipped).
The quick-n-dirty solution is to have the custom UIView assume that the parent is a UIScrollView and get the content size through it, but I'm looking for a better solution that doesn't involve make such assumptions.
This should do the trick
CGRect visibleRect = CGRectIntersection(self.frame, superview.bounds);
Use that in the UIView and it should get you the rectangle (if any) that represents the visible section of that view in it's superview (The UIScrollView). I'm assuming here that there is no view between them in the hierarchy, but if there is, fiddling the code should be trivial.
Hope I could help!
It would help if you would give more info on what is that you are trying to accomplish.
If you want to know the size of the super view you can do this:
CGRect superFrame = [self superview].frame;
Swift 3
extension UIView {
var visibleRect: CGRect? {
guard let superview = superview else { return nil }
return frame.intersection(superview.bounds)
}
}