How do I add a UIview to an imageView while ensuring that the contents of the UIView are inside the it's frame? - ios

I have a superview which contains a ImageView, a testView, and some buttons. I created a UIView which contains ImageView2 and a removebutton.
When I add UIView to UIImageView, the contents of UIView are not in the frame of UIView. Because of that, I cannot apply pan gesture recognizer.
I have tried to apply constraints and to change the frame and centre of ImageView2.
Below is the code I am using to create the above mentioned UIView. How do I ensure that the contents of the UIView are visible in the frame of the UIView?
let rect = CGRect(x: self.imageView.center.x-30, y: self.imageView.center.y-30, width: 80, height: 80)
testview = UIView(frame: rect)
testview.layer.cornerRadius = testview.frame.width/2
testview.backgroundColor = UIColor.blackColor()
testview.clipsToBounds = true
imageView2 = UIImageView(frame: CGRect(x: testview.frame.minX+10, y: testview.frame.minY+10, width: 60, height: 60))
let rect2 = CGRect(x: self.testview.frame.maxX-17, y: self.testview.frame.minY, width: 20, height: 20)
removeButton = UIButton(frame: rect2)
removeButton.layer.cornerRadius = removeButton.frame.width/2
removeButton.backgroundColor = UIColor.blackColor()
removeButton.clipsToBounds = true
imageView2.layer.cornerRadius = imageView2.frame.width/2
imageView2.userInteractionEnabled = true
imageView2.clipsToBounds = true
testview.alpha = 0.3
imageView2.center = testview.center
imageView2.center = testview.center
testview.addSubview(imageView2)
testview.addSubview(removeButton)
testview.bringSubviewToFront(imageView2)
imageView.addSubview(testview)

The problem is that lines like this do not do what you think:
let rect = CGRect(x: self.imageView.center.x-30, y: self.imageView.center.y-30, width: 80, height: 80)
// ... and ...
imageView2.center = testview.center
The center of a view is in its frame coordinates - it has to do with how the view is placed in its superview. But the position of a subview must be described in terms of its superviews bounds, not its frame. Its bounds are its internal coordinates, which is what you want.
Let's take the simplest case: how to center a subview in a superview. This is not the way:
imageView2.center = testview.center
You see the problem? testview.center is where testview is located in its superview; it is not the internal center of testview, which is what you want. The internal center of testview comes from its bounds. This is the way:
let c = CGPointMake(testview.bounds.midX, testview.bounds.midY)
imageView2.center = c

Related

Blend UIView (Overlay) with app background

I would like to blend a UIView with my app's background, using a special blend mode (in my case, the Overlay mode). However, the view to blend is contained in a complex hierarchy of views.
Blending a view with its direct siblings can be achieved using view.layer.compositingFilter = "overlayBlendMode", but the view won't blend with non-siblings views, like the app background.
To recreate the problem, I made the following playground:
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let parentView = UIView()
parentView.backgroundColor = .purple
// Child view
let childView = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 200))
childView.layer.borderColor = UIColor.orange.cgColor
childView.layer.borderWidth = 3
parentView.addSubview(childView)
// Child child view
let childChildView = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))
childChildView.backgroundColor = .white
childChildView.layer.compositingFilter = "overlayBlendMode"
childView.addSubview(childChildView)
self.view = parentView
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
We can see here that the child child view, in white, is not blended:
Whereas the view should appear blended like this (the border should not change color):
To create the second picture, I applied the compositing filter on the childView instead of the childChildView, which will blend all the other subviews — therefore it's not what I want. I just want this specific view to be blended.
Note: this view is supposed to move, because it's inside a UIScrollView.
EDIT: More complex example with image background and scrollviews
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let parentView = UIView()
// Background image
let backgroundImageView = UIImageView(image: UIImage(named: "image.jpg")!)
backgroundImageView.frame = UIScreen.main.bounds
parentView.addSubview(backgroundImageView)
// Page view (horizontal scrollview)
let pageView = UIScrollView(frame: CGRect(x: 50, y: 50, width: 200, height: 200))
pageView.contentSize = CGSize(width: 600, height: 200)
pageView.flashScrollIndicators()
pageView.layer.borderColor = UIColor.orange.cgColor
pageView.layer.borderWidth = 3
parentView.addSubview(pageView)
// Child view (vertical scrollview)
let childView = UIScrollView(frame: CGRect(x: 20, y: 20, width: 100, height: 150))
childView.contentSize = CGSize(width: 100, height: 300)
childView.layer.borderColor = UIColor.green.cgColor
childView.layer.borderWidth = 3
pageView.addSubview(childView)
// Child child view
let childChildView = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))
childChildView.backgroundColor = .white
childChildView.layer.compositingFilter = "overlayBlendMode"
childView.addSubview(childChildView)
self.view = parentView
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
UPDATE 2:
I've tried several ways including adding layers or creating custom image filters that use the background image as input image but none of these solutions got the desired result. The main problem was always the view hierarchy.
I may have found a solution by using a generated image of the views or the actual background image as the content background of the childView once the childChildView is being created but before being displayed. I've changed your example code a bit to add a scroll view and background image in the parentView. See if this works for you / is your desired result:
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let parentView = UIView()
parentView.backgroundColor = .purple
let imageName = "image.jpg"
let image = UIImage(named: imageName)
let imageWidth = Int((image?.size.width)!)
let imageheight = Int((image?.size.height)!)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 50, y: 50, width: imageWidth , height: imageheight)
parentView.addSubview(imageView)
// Child view as UIScrollView
let childView = UIScrollView(frame: CGRect(x: 55, y: 55, width: imageWidth - 10, height: imageheight - 10 ))
childView.contentSize = CGSize(width: imageWidth - 10, height: 5000)
childView.layer.borderColor = UIColor.orange.cgColor
childView.flashScrollIndicators()
childView.layer.borderWidth = 10
parentView.addSubview(childView)
// ChildChild view
let childChildView = UIView(frame: CGRect(x: 15, y: 100, width: 85, height: imageheight - 180))
childChildView.layer.compositingFilter = "overlayBlendMode"
childChildView.backgroundColor = .white
//Creating a static image of the background views BEFORE adding the childChildView.
let format = UIGraphicsImageRendererFormat()
format.scale = 1
format.preferredRange = .standard ///color profile
///Change the imageView to the parentView size of the app. Not available if not set in the playground.
let renderer = UIGraphicsImageRenderer(size: imageView.bounds.size, format: format)
let imageBG = renderer.image { context in
///This draws all subviews of the parentView one after the other.
///Because the background image is not a parent of our current view, otherwise childView.drawHierachy would have been enough
for subview in parentView.subviews {
///Skip specific views or view classes you don't want to be added to the image. or if you only need the parentView itself rendered remove the for in loop.
subview.drawHierarchy(in: imageView.bounds, afterScreenUpdates: true)
}
}
//Adding the static background image. This could simply also be the actual image: UIImage if no other views are supposed to be used.
childView.layer.contents = imageBG.cgImage
childView.addSubview(childChildView)
self.view = parentView
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
It results in the following:
UPDATE:
The colors in the images are misleading, as you could assume a normal transparency effect would be the same. But the overlayBlendMode is quite different as Coconuts has pointed out. I assume the issue is that the compositingFilter only works with the view below, even if this view is transparent.
I tried finding a workaround by using a mask that cuts out a square of the size of the childchild from the childview. But this also didn't work as the mask is also applied to all subviews. The only way I got it to work is by making the childchildview a sibling of childview instead, or a direct subview of the background view. But not sure if this will be possible in the complex view hierarchy mentioned by Coconuts.
// Sibling view with adjusted x and y
let childChildView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
childChildView.backgroundColor = .white
childChildView.layer.compositingFilter = "overlayBlendMode"
parentView.addSubview(childChildView)
MISC:
To only get the visual result of the sample images, not actually using the overlayBlendMode filter as asked by Coconut.
If you only need to blend the color you could change the alpha value of the color.
// Child child view
let childChildView = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))
childChildView.backgroundColor = UIColor(white: 1, alpha: 0.5)
//childChildView.layer.compositingFilter = "overlayBlendMode"
childView.addSubview(childChildView)
Or try this:
// Child child view
let childChildView = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))
childChildView.backgroundColor = .white
childChildView.layer.opacity = 0.5
childView.addSubview(childChildView)
ADDITIONAL ATTEMPTS WHEN HAVING SEVERAL SCROLL VIEWS:
This is an attempt to solve the from Coconut added more complicated view hierarchy with multiple scroll views. The performance needs to be improved or the part that adjusts the background image of the background image layer needs to run in sync when the app is updating (redrawing) its views. At the moment it's lagging behind a bit.
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let parentView = UIView()
// Background image
let backgroundImageView = UIImageView(image: UIImage(named: "image.jpg")!)
backgroundImageView.frame = UIScreen.main.bounds
parentView.addSubview(backgroundImageView)
// Page view (horizontal scrollview)
let pageView = UIScrollView(frame: CGRect(x: 50, y: 50, width: 200, height: 200))
pageView.contentSize = CGSize(width: 600, height: 200)
pageView.flashScrollIndicators()
pageView.layer.borderColor = UIColor.yellow.cgColor
pageView.layer.borderWidth = 3
pageView.clipsToBounds = true
parentView.addSubview(pageView)
// Child view (vertical scrollview)
let childView = UIScrollView(frame: CGRect(x: 20, y: 20, width: 100, height: 150))
childView.contentSize = CGSize(width: 100, height: 300)
childView.layer.borderColor = UIColor.red.cgColor
childView.layer.borderWidth = 3
pageView.addSubview(childView)
// Child child view
let childChildView = UIView(frame: CGRect(x: 50, y: 50, width: 50, height: 50))
//Child child view foreground sublayer
let childChildFrontLayer = CALayer()
childChildFrontLayer.frame = childChildView.frame.offsetBy(dx: -75, dy: -50)
childChildFrontLayer.backgroundColor = UIColor.white.cgColor
childChildFrontLayer.compositingFilter = "overlayBlendMode"
//Child child view background sublayer
let childChildBackLayer = CALayer()
childChildBackLayer.contents = UIImage(named: "image.jpg")?.cgImage
var absolutFrame = parentView.convert(childChildView.frame, from: childView)
childChildBackLayer.frame = CGRect(x: -absolutFrame.minX, y: -absolutFrame.minY, width: backgroundImageView.frame.width, height: backgroundImageView.frame.height)
childChildView.layer.addSublayer(childChildBackLayer)
childChildView.layer.addSublayer(childChildFrontLayer)
childView.addSubview(childChildView)
//Checking for any scrolling. Is slightly faster then the scollview delegate methods but might cause main thread checker warning.
DispatchQueue.global(qos: .userInteractive).async {
while true {
if pageView.isDragging || pageView.isTracking || pageView.isDecelerating || childView.isDragging || childView.isTracking || childView.isDecelerating {
absolutFrame = parentView.convert(childChildView.frame, from: childView)
DispatchQueue.main.async {
childChildBackLayer.frame = CGRect(x: -absolutFrame.minX, y: -absolutFrame.minY, width: backgroundImageView.frame.width, height: backgroundImageView.frame.height)
}
}
}
}
self.view = parentView
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Is the issue related to the child view background being clear and therefore 'blending' to give the white colour. Could set the child view background colour to be equal to the app background and then then just blend the childView within the childChildView?

titleView in NavigationItem doesn't consider frame height in iOS 11

I've updated to Xcode 9, and I have a titleView in my NavigationItem created in this way:
let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 25))
logo.image = UIImage.logo
logo.contentMode = .scaleAspectFit
self.navigationItem.titleView = logo
The result is that it doesn't consider anymore the frame height.
we can control the size and position of UINavigationbar titleview. Don't use to set the imageview as titleview directly. in here create a custom UIView and then set the frame as what you need requirement and add the logo as its subview
do like
let supportVie = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 25))
// Here you can set View width and height as per your requirement for displaying supportVie position in navigationbar
//supportVie.backgroundColor = UIColor.red
let logo = UIImageView(image: UIImage.logo ) //UIImage(named: "SelectAnAlbumTitleLettering")
logo.frame = CGRect(x: 45, y: 5, width: supportVie.frame.size.width, height: supportVie.frame.size.height)
// customize the origin as (45,5) but can pass them as your requirement.
supportVie.addSubview(logo)
//supportVie.contentMode = .center;
navigationItem.titleView = supportVie

Add a complex boarder to UIImageView

How do I add boarder like in the below image (in Objective-C ) to UIImageView. I tried using UIBezierPath but wasn't successful.
Create a UIView (square in dimensions), add corner radius = 1/2 times its side.
Now add the UIImageView as a subview to this UIView.
As the image is circular in shape, so a simpler appraoch to the solution to your problem is to add corner radius to your UIVIew.
Below is the code I used:
let circleView: UIView = UIView(frame: CGRect(x: 0,
y: 0,
width: 100,
height: 100))
circleView.center = view.center
circleView.backgroundColor = .lightGray
circleView.layer.cornerRadius = 50
view.addSubview(circleView)
let imageView: UIImageView = UIImageView(frame: CGRect(x: 0,
y: 0,
width: 100,
height: 100))
imageView.image = UIImage(named: "F8FIs.png")
circleView.addSubview(imageView)
Please note that I added lightGray color to circle view for clarity.
And here is the screenshot of how it looks:

Unable to properly configure UIScrollView (Offset on top)

I have been fighting with this all morning and can't seem to find a solution. I have created a UIImageView, filled it with red, then added it to a UIScrollView and set the contentSize to the size of the UIImageView. If I print the contentOffset i see (0, 0) and if I print the contentSize and the UIImageView.frame.size they are the same but the red "image" always appears smaller than what the scrollView thinks the contentSize is.
If I scroll all the way to the top I see a cyan stripe about 100 pixels high above the red image and the scroll bar will not make it all the way to the top of what I believe the top of my scroll view to be. Although the top of the scroll bar does line up with the top of my red window so it would seem as though the scroll view is confused as to where it actually lives. Or more likely, I'm confused
Here is my what seems like very simple code...
imgHorizon = UIImage.init(named:"horizon")!
imgBezel = UIImage.init(named:"bezel_transparent")!
imgWings = UIImage.init(named:"wings_transparent")!
imgViewHorizon = UIImageView.init()
imgViewBezel = UIImageView.init()
imgViewWings = UIImageView.init()
svHorizon = UIScrollView.init()
super.init(coder: aDecoder)
imgViewHorizon = UIImageView(frame: CGRect(x: 0, y: 0, width: imgBezel.size.width, height: imgHorizon.size.height))
imgViewHorizon.backgroundColor = UIColor.red
imgViewBezel = UIImageView(frame: CGRect(x: 0, y: 0, width: imgBezel.size.width, height: imgBezel.size.height))
imgViewBezel.contentMode = UIViewContentMode.center
imgViewBezel.clipsToBounds = true
imgViewBezel.image = imgBezel
imgViewWings = UIImageView(frame: CGRect(x: 0, y: 0, width: imgBezel.size.width, height: imgBezel.size.height))
imgViewWings.contentMode = UIViewContentMode.center
imgViewWings.clipsToBounds = true
imgViewWings.image = imgWings
svHorizon = UIScrollView(frame: CGRect(x: 0, y: 0, width: imgBezel.size.width, height: imgBezel.size.width))
svHorizon.contentSize = CGSize(width: imgBezel.size.width, height: imgHorizon.size.height)
svHorizon.contentMode = UIViewContentMode.scaleToFill
svHorizon.bounces = false
svHorizon.backgroundColor = UIColor.cyan
svHorizon.contentOffset = CGPoint(x: 0, y: 0)
svHorizon.addSubview(imgViewHorizon)
addSubview(svHorizon)
addSubview(imgViewBezel)
addSubview(imgViewWings)
From the discussion in the comments it turns out that the Adjust Scroll View Insets option was checked in the attributes inspector of the ViewController. Unchecking it resolved the problem. Have a look at the image below. You need to uncheck the highlighted option.

Stop affine transform from applying on subview

I have a UIView that holds a UILabel inside.
After applying affine transform on the UIView using:
myView.transform = CGAffineTransformMakeScale(4, 4);
My UILabel (which is a sub view to myView) grows as well.
Is there a way to prevent this?
i tried:
1) Using the CGAffineTransformIdentity flag on the label.
2) Adding a superview to myView and adding myView as superview's subview, and the label as a subview to the superview (and not myView).
Non of them seem to be working, the label keeps growing.
Any ideas?
You answered your own question with option 2. Not sure why it's not working since you did not supply any code. The playground code below shows it will work. Uncomment out the last line to transform the subview but not the label.
import UIKit
import XCPlayground
let superview = UIView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
XCPlaygroundPage.currentPage.liveView = superview
superview.backgroundColor = UIColor.redColor()
let view = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
view.backgroundColor = UIColor.greenColor()
superview.addSubview(view)
let label = UILabel(frame: CGRect(x: 20, y: 10, width: 40, height: 40))
label.text = "Hello"
superview.addSubview(label)
//view.transform = CGAffineTransformMakeScale(2, 2)

Resources