I'm trying to register a tap inside an UIScrollView but can't seem to get it work. I tried everything I've found on here to no success. I'm using a subclass of UIImageView to add an identifier to it which shouldn't be the problem. Can't seem to get it to work with the default UIImageView class either. "didTapImage" just does not get executed no matter what I do.
func fillSelectionView(){
let imageNameArray = ["entdecken", "erleben", "erinnern"]
imageArray = [UIImage(named: imageNameArray[0]), UIImage(named: imageNameArray[1]), UIImage(named: imageNameArray[2])] as! [UIImage]
for i in 0..<imageArray.count{
let imageView = UIImageViewWithIdentifier()
imageView.image = imageArray[i]
imageView.contentMode = .scaleAspectFit
imageView.setIdentifier(ident: imageNameArray[i])
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(UIGestureRecognizer(target: self, action: Selector(("didTapImage"))))
let xPosition = self.selectionView.frame.width * CGFloat(Double(i))
imageView.frame = CGRect(x: xPosition, y: 0, width: selectionView.frame.width, height: selectionView.frame.height)
selectionView.contentSize.width = self.selectionView.frame.width * CGFloat((Double(i) + 1))
selectionView.addSubview(imageView)
}
}
func didTapImage(gesture: UIGestureRecognizer) {
let point = gesture.location(in: gesture.view)
let imageViewTouched = gesture.view as! UIImageViewWithIdentifier
let imageViewIdent = imageViewTouched.getIdentifier()
print(point)
print("touched" + imageViewIdent)
}
Related
I just want to show image according to image size if the image height is grater then width then image will show horizentally or if the width is grater then height then it will show in centre.
I have already tried and I am showing my code. What I am trying ?
override func viewDidLoad() {
super.viewDidLoad()
var profileImagesData:Array<UIImage> = []
for i in 0..<profileImages.count {
// for venueImageTemp in profileImages {
var statusDict = profileImages[i] as! Dictionary<String,Any>
var imageUrl = String(format:"%#",statusDict["imageId"] as! CVarArg)
print(imageUrl)
if imageUrl.contains("cloudinary.com") {
let imgNameArr = imageUrl.components(separatedBy: "upload/")
print(imgNameArr)
let subFisrtStr = imgNameArr[0]
print(subFisrtStr)
let subStr = imgNameArr[1]
print(subStr)
let subImgNameArr = subStr.components(separatedBy: "/")
print(subImgNameArr)
let subNameStr = subImgNameArr[1]
print(subNameStr)
imageUrl = ""
imageUrl = subFisrtStr + "upload/h_600,w_600/" + subNameStr
print(imageUrl)
}
let url = URL(string: imageUrl)
print(url)
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in
let image = UIImage(data: (data)!)
profileImagesData.append(image!)
}
let imageView = CYCImageScrollView(images: profileImagesData, frame: CGRect(x: 0, y: 20, width: self.view.frame.size.width, height: self.view.frame.size.height-150), pageColor: UIColor.lightGray, currentPageColor: UIColor.orange)
// imageView.layer.cornerRadius = 30
imageView.backgroundColor = UIColor.clear
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.layer.masksToBounds = true
self.view.addSubview(imageView)
}
I just want to show image according to their sizes.
Use content mode scaleAspectFill instead of scaleAspectFit
imageView.contentMode = .scaleAspectFill
I got here such an error:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
What is wrong with my code? I try to add image to navcontroller , I have here image as you can see.
func addNavBarImage() {
let nc = navigationController!
let image = UIImage(named: "2.png")
let imageView = UIImageView(image: image)
let bwidth = nc.navigationBar.frame.size.width
let bheight = nc.navigationBar.frame.size.height
let bannerx = bwidth/2 - (image?.size.width)!/2
let bannery = bheight/2 - (image?.size.height)!/2
imageView.frame = CGRect(x: bannerx, y: bannery, width: bwidth, height: bheight)
imageView.contentMode = .scaleAspectFit
navigationItem.titleView = imageView
}
You get this error message when you don´t have a legit image added to your let image = UIImage(named: "2000"). It is nil. Your code crashes on let bannerx = bwidth/2 - (image?.size.width)!/2. Make sure you have the right image before you continue your execution after that row.
Replace:
let image = UIImage(named: "2.png")
With:
guard let image = UIImage(named: "2") else { return }
By doing this you don´t need the to force optional use the following rows, so replace the below rows for bannerx and bannery with yours:
let bannerx = bwidth/2 - (image.size.width)/2
let bannery = bheight/2 - (image.size.height)/2
I'm trying to create a view of a "match" image and the "match price" label in the top right corner of the match image. So far everything works fine- I create the image in the container view, I create a UIImageView for the background of my price label, but when I create the actual label and customize it, it takes forever to load in my app (that is to say, everything loads- the match image, the price label background image, but not the actual label detailing the price). Can anyone spot where in my code I'm going wrong?
func setupMiniContentScroll(contentScroll: UIScrollView) {
let scalar:Double = 6/19
let contentViewDimension = contentScroll.frame.width * CGFloat(scalar)
let contentScrollWidth = CGFloat(LocalUser.matches.count) * (contentViewDimension + CGFloat(12)) - CGFloat(12)
contentScroll.backgroundColor = UIColorFromHex(0x34495e)
for index in 0..<LocalUser.matches.count {
let match = LocalUser.matches[index]
MatchesManager.globalManager.retrieveMatchThumbnail(match) { img, error in
if let img = img {
//create the mini matches views
let xOrigin = index == 0 ? 12 : CGFloat(index) * contentViewDimension + (CGFloat(12) * CGFloat(index) + CGFloat(12))
let contentFrame = CGRectMake(xOrigin, 10, contentViewDimension, contentViewDimension)
let contentView = self.makeMiniContentView(contentFrame, image: img, matchedPrice: match.matchedPrice)
contentView.match = match
let tap = UITapGestureRecognizer(target: self, action: #selector(BrowseViewController.toggleItemInfo(_:)))
contentView.addGestureRecognizer(tap)
//update the contentScrollView
dispatch_async(dispatch_get_main_queue()) {
contentScroll.addSubview(contentView)
contentScroll.contentSize = CGSizeMake(contentScrollWidth + CGFloat(16), contentScroll.frame.height)
}
}
}
}
}
//functions to create labels and imgViews for MiniMyMatches
func makeMiniContentView(frame: CGRect, image: UIImage, matchedPrice: Int) -> ItemContainer {
let containerView = ItemContainer(frame: frame)
//create the item image
let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: containerView.frame.width, height: containerView.frame.height))
imgView.image = image
imgView.layer.cornerRadius = 5
imgView.layer.masksToBounds = true
imgView.userInteractionEnabled = true
//create the price label
dispatch_async(dispatch_get_main_queue()) {
let priceLabel = self.makeMiniPriceLabel(containerView, matchedPrice: matchedPrice)
containerView.addSubview(imgView)
containerView.addSubview(priceLabel)
}
return containerView
}
func makeMiniPriceLabel(containerView: ItemContainer, matchedPrice: Int) -> UIView {
//price label var
let priceLabelFrame = CGRectMake(containerView.frame.size.width - 35, -7, containerView.frame.size.width * 0.50, containerView.frame.size.height * 0.35)
//create the price container
let priceContainer = UIImageView(frame: priceLabelFrame)
priceContainer.image = UIImage(named: "venn.png")
//create the price label
let priceLabel = UILabel(frame: CGRect(x: 3, y:0, width: priceContainer.frame.width, height: priceContainer.frame.height))
priceLabel.text = "$\(matchedPrice)"
priceLabel.numberOfLines = 1
priceLabel.textColor = UIColor.whiteColor()
priceLabel.font = priceLabel.font.fontWithSize(20)
priceContainer.addSubview(priceLabel)
return priceContainer
}
My guess is that the closure for your retrieveMatchThumbnail function is being called on a background thread. You have code in that closure that is manipulating UI objects. I would move ALL the UI code inside your call to dispatch_async():
MatchesManager.globalManager.retrieveMatchThumbnail(match) { img, error in
if let img = img {
//create the mini matches views
let xOrigin = index == 0 ? 12 : CGFloat(index) * contentViewDimension + (CGFloat(12) * CGFloat(index) + CGFloat(12))
let contentFrame = CGRectMake(xOrigin, 10, contentViewDimension, contentViewDimension)
//update the contentScrollView
dispatch_async(dispatch_get_main_queue()) {
let contentView = self.makeMiniContentView(contentFrame, image: img, matchedPrice: match.matchedPrice)
contentView.match = match
let tap = UITapGestureRecognizer(target: self, action: #selector(BrowseViewController.toggleItemInfo(_:)))
contentView.addGestureRecognizer(tap)
contentScroll.addSubview(contentView)
contentScroll.contentSize = CGSizeMake(contentScrollWidth + CGFloat(16), contentScroll.frame.height)
}
}
}
I'm trying to add a tap gesture recognizer to some UIImages that are in a side scrollview, but the images flat out won't recognize the tap and I can't see where I went wrong. I've tried "scrollView.bringSubViewToFront(imgView)" because I figured they might be getting buried in layers of other views, but that didn't do the trick either. "contentView" is the UIImageView in question, where my scrollView is just a collection of those. Any help here would be appreciated, thank you.
//function to create contentScrollView for MiniMatches
func setupMiniContentScroll(contentScroll: UIScrollView) {
let scalar:Double = 4/19
let contentViewDimension = contentScroll.frame.width * CGFloat(scalar)
let contentScrollWidth = CGFloat(LocalUser.matches.count) * (contentViewDimension + CGFloat(12)) - CGFloat(12)
let matchManager = MatchesManager()
for index in 0..<LocalUser.matches.count {
let match = LocalUser.matches[index]
matchManager.retrieveMatchThumbnail(match) { img, error in
if let img = img {
//create the mini matches views
let xOrigin = index == 0 ? 12 : CGFloat(index) * contentViewDimension + (CGFloat(12) * CGFloat(index) + CGFloat(12))
let contentFrame = CGRectMake(xOrigin, 10, contentViewDimension, contentViewDimension)
let contentView = self.makeMiniContentView(contentFrame, image: img, matchedPrice: match.matchedPrice)
let tap = UITapGestureRecognizer(target: self, action: #selector(BrowseViewController.toggleItemInfo(_:)))
contentView.addGestureRecognizer(tap)
self.miniMatchContainer.append(contentView)
//update the contentScrollView
dispatch_async(dispatch_get_main_queue()) {
let contentLabelFrame = CGRect(x: xOrigin, y: contentFrame.height + 15, width: contentFrame.width, height: 20)
let contentLabel = self.makeMiniContentLabel(contentLabelFrame, itemName: match.itemName)
let priceLabel = self.makeMiniPriceLabel(contentFrame, matchedPrice: match.matchedPrice)
contentScroll.addSubview(contentView)
contentScroll.addSubview(contentLabel)
contentScroll.addSubview(priceLabel)
contentScroll.contentSize = CGSizeMake(contentScrollWidth + CGFloat(16), contentScroll.frame.height)
}
}
}
}
}
Did you set UIImage property userInteractionEnabled to true?
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)