calculating UIWebView height with images gives wrong answer - swift

I found how to calculate dynamic uiwebview height according to its content. My code is :
println("webViweDidFinish started")
var frame:CGRect = myWebView.frame
frame.size.height = 1
var fittingSize :CGSize = myWebView.sizeThatFits(CGSizeZero)
frame.size = fittingSize
myWebView.frame = frame
var contentsizeHeight = webView.scrollView.contentSize.height
var yCoordinateOfWebView = myWebView.frame.origin.y
var contentHeight: CGFloat = webView.scrollView.contentSize.height;
myScrollView.contentSize = CGSizeMake(self.view.frame.width, yCoordinateOfWebView + contentsizeHeight + labelAuthorOfArticle.frame.height) //
UIView.animateWithDuration(0.5, animations: {
self.heightConstraints.constant = fittingSize.height
self.myWebView.layoutIfNeeded()
self.myScrollContentView.layoutIfNeeded()
})
self.activityIndicator.stopAnimating()
If I use this approach:
var height:NSString! = webView.stringByEvaluatingJavaScriptFromString("document.height;")
var heightInFloat = height.floatValue
How to convert height to CGFloat? I can only convert it to float as you see.
The problem is that when webview has too many images the height is calculated wrong. Oppositely when there is no image height is calculated right. When I reload the function, the second time it calculates right (with images). Here is content of string that I am loading:
class func formatContentText(inout text: NSString)-> NSString{
text = text.stringByReplacingOccurrencesOfString("src=\"", withString: "src=\"http://dixinews.kz")
var deviceWidth = "300"
text = "<html><head><meta name = \"viewport\" content = \"user-scalable=no, width=" + deviceWidth + " , maximum-scale=1.0\"><style>img{max-width:100%%;height:auto !important;width:auto !important;};</style></head><body>" + text + "</body></html>"
return text
}

I used approach with javascript. Here is my code:
func webViewDidFinishLoad(webView: UIWebView) {
var frame:CGRect = myWebView.frame
// javascript
var height:NSString! = webView.stringByEvaluatingJavaScriptFromString("document.height;")
var heightInFloat = height.floatValue // convert to float
var heightINCGFloat = CGFloat(heightInFloat) convert to cgfloat
frame.size.height = heightINCGFloat //set heigh
myWebView.frame = frame // set frame
myWebView.scrollView.contentSize.height = myWebView.frame.height
var contentsizeHeight = webView.scrollView.contentSize.height
var yCoordinateOfWebView = myWebView.frame.origin.y
myScrollView.contentSize = CGSizeMake(self.view.frame.width, yCoordinateOfWebView + contentsizeHeight + labelAuthorOfArticle.frame.height) //
UIView.animateWithDuration(0.5, animations: {
self.heightConstraints.constant = heightINCGFloat
self.myWebView.layoutIfNeeded()
self.myScrollContentView.layoutIfNeeded()
})
self.activityIndicator.stopAnimating()
}

Related

Layout programmatically created UILabels in a UIView

I have this:
Created via this piece of code:
// Add hashtag collection to a post
func addHashtags(container: UIView, constraint: NSLayoutConstraint) -> Void {
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width - 16 - 16
var currentOriginX: CGFloat = 0
var currentOriginY: CGFloat = 0
for j in 0..<self.pseudo.count {
if currentOriginY < 144 {
// Create a new label
let labelHashtag = RoundedLabel()
labelHashtag.rounded = true
tagLabels.append(labelHashtag)
print(tagLabels.count)
// Set its properties (title, colors, corners, etc)
labelHashtag.text = pseudo[j] as? String
labelHashtag.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
labelHashtag.textAlignment = .center
labelHashtag.textColor = UIColor.black
labelHashtag.backgroundColor = UIColor.white
labelHashtag.layer.borderColor = UIColor(red:0.88, green:0.88, blue:0.88, alpha:1.0).cgColor
labelHashtag.layer.borderWidth = 1
// Set its frame width and height
labelHashtag.frame.size.width = labelHashtag.intrinsicContentSize.width + tagPadding
labelHashtag.frame.size.height = tagHeight
// Add it to the scroll view
container.addSubview(labelHashtag)
// If current X + label width will be greater than container view width
// .. move to next row
if (currentOriginX + labelHashtag.frame.width > screenWidth) {
tagLabels[0].textColor = .red
print("übrig")
print(screenWidth - currentOriginX)
currentOriginX = 0
currentOriginY += tagHeight + tagSpacingY
}
// Set the btn frame origin
labelHashtag.frame.origin.x = currentOriginX
labelHashtag.frame.origin.y = currentOriginY
// Increment current X by btn width + spacing
currentOriginX += labelHashtag.frame.width + tagSpacingX
} else if currentOriginY == 90 {
}
// Update container view height
constraint.constant = currentOriginY + tagHeight
}
container.layoutIfNeeded()
}
I want to center all items in each row. I imagine I have to calculate the remaining width of my UIView and add a margin to the first item.
How can I add a margin to my UILabel? I can access it via tagLabels[0] and I think I know how to calculate the remaining width, but I don't know how I can add the margin to it.

make disable , ui button random position swift

there is a UIButton in view controller and when button clicked , UIButton move with random position in View Controller . The question it is how i can make disable movable ability when clicked again on button ?
this is moveable Method :
func randomPosition() {
self.movable_Button.layer.cornerRadius = 10
let buttonWidth = movable_Button.frame.width
let buttonHeight = movable_Button.frame.height
let viewWidth = movable_Button.superview!.bounds.width
let viewHeight = movable_Button.superview!.bounds.height
let xwidth = viewWidth - buttonWidth
let yheight = viewHeight - buttonHeight
let xPosition = CGFloat(arc4random_uniform(UInt32(xwidth)))
let yPosition = CGFloat(arc4random_uniform(UInt32(yheight)))
movable_Button.center.x = xPosition + buttonWidth / 2
movable_Button.center.y = yPosition + buttonHeight / 2
}
I think you have programmed something like
func onButtonClicked() {
randomPosition()
}
so you can make a new variable:
var clickedButton = false
func onButtonClicked() { // i know this is not the correct function, but i think you know what i mean ;)
if clickedButton == false {
randomPosition()
} else {
clickedButton = true
}
}

Multiple subviews being added to UIScrollview

On my users profile page, there is a scrollview users slide across to see more photos. Everything works with adding the photos but the problem is that each image added to the scrollviews subview, is added twice. This is the code I am using to populate the scrollview. I currently have an Imageview embed inside the scrollview on storyboard and use that as the default if user has no photos. The at the bottom should show the bug. I have tried using a combination of clipstobounds, scaleaspectfit, and setting background color to clear but nothing stops from showing an additional image in the background. Any ideas would be appreciated. On a side note, the bug is only noticed on the iphone 8 plus
var pages: Int = 1
var numPhotos: CGFloat = 1
var position: CGFloat = 1
let scrollWidth: CGFloat = profileImage.frame.width
let scrollHeight: CGFloat = profileImage.frame.height
let scrollY: CGFloat = profileImage.frame.origin.y
if let profileImg = user.profileImage {
profileResource = ImageResource(downloadURL: URL(string: profileImg)!, cacheKey: profileImg)
profileImage.kf.setImage(with: profileResource)
} else {
profileImage.image = #imageLiteral(resourceName: "requests_icon")
}
nameLbl.text = user.fullName
influenceLbl.text = "\(user.score)"
followersLbl.text = "\(user.followers)"
followingLbl.text = "\(user.following)"
if let image1 = user.photo1 {
let imageOne = UIImageView(frame: CGRect(x: scrollWidth * position, y: scrollY, width: scrollWidth, height: scrollHeight))
imageOne.contentMode = .scaleAspectFit
photo1Resource = ImageResource(downloadURL: URL(string: image1)!, cacheKey: image1)
imageOne.kf.setImage(with: photo1Resource)
pages = pages + 1
numPhotos = numPhotos + 1
position = position + 1
scrollView.addSubview(imageOne)
} else {
}
if let image2 = user.photo2 {
let imageTwo = UIImageView(frame: CGRect(x: scrollWidth * position, y: scrollY, width: scrollWidth, height: scrollHeight))
imageTwo.contentMode = .scaleAspectFit
photo2Resource = ImageResource(downloadURL: URL(string: image2)!, cacheKey: image2)
imageTwo.kf.setImage(with: photo2Resource)
pages = pages + 1
numPhotos = numPhotos + 1
position = position + 1
scrollView.addSubview(imageTwo)
} else {
}
if let image3 = user.photo3 {
let imageThree = UIImageView(frame: CGRect(x: scrollWidth * position, y: scrollY, width: scrollWidth, height: scrollHeight))
imageThree.contentMode = .scaleAspectFit
photo3Resource = ImageResource(downloadURL: URL(string: image3)!, cacheKey: image3)
imageThree.kf.setImage(with: photo3Resource)
pages = pages + 1
numPhotos = numPhotos + 1
position = position + 1
scrollView.addSubview(imageThree)
} else {
}
scrollView.contentSize = CGSize(width: profileImage.frame.width * numPhotos, height: scrollHeight)
scrollView.delegate = self
scrollView.contentMode = .scaleAspectFit
scrollView.clipsToBounds = true
pageControl.numberOfPages = pages
pageControl.currentPage = 0
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){
let pageWidth:CGFloat = scrollView.frame.width
let currentPage:CGFloat = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth) + 1
self.pageControl.currentPage = Int(currentPage)
}

TextView Behavior issue (Swift)

Been going mad for days trying to fix this problem.
** Everytime a new line is created the textView jumps up.**
Inserting another character, after the line is created, adjusts the textView correctly to its frame.
So the issue is only when a new line is created.
It's a minor issue but its quite irritating.
func textViewDidChange(textView: UITextView) {
print("text view did change\n")
let fieldStatus = textView.text
let textViewFixedWidth: CGFloat = self.textView.frame.size.width
let newSize: CGSize = self.textView.sizeThatFits(CGSizeMake(textViewFixedWidth, CGFloat(MAXFLOAT)))
var newFrame: CGRect = self.textView.frame
var textViewYPosition = self.textView.frame.origin.y
var heightDifference = self.textView.frame.height - newSize.height
self.textView.frame = newFrame
self.textView.updateConstraintsIfNeeded()
self.UserMessageView.updateConstraintsIfNeeded()
self.UserMessageView.frame.height.floatingPointClass
UserMessageViewHeightConstraint.constant = newSize.height + 8
if UserMessageViewHeightConstraint.constant >= 250 {
println("stop growing")
let stopGrowth: CGFloat = self.UserMessageView.frame.height
let currentHeight = self.textView.frame.height
UserMessageViewHeightConstraint.constant = stopGrowth
}
if countElements(fieldStatus) >= 500 {
textView.deleteBackward()
}
println("\(countElements(fieldStatus))")
}
Has anyone encountered this before?
/Will

Delete ImageView From SubScrollView In Swift

I am having main ScrollView with pages Enable..Under that I have Subscrollviews and ImageView to display images..I want to Delete Selected image from main scrollview..I don't have any idea to how to get that selected imageView from scrollview and remove it...Here is my code...
func createScroll()
{
var arrayImage = NSUserDefaults.standardUserDefaults().objectForKey("ImageArray") as NSMutableArray
var index = NSUserDefaults.standardUserDefaults().objectForKey("Index") as Int
var scroll = UIScrollView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height))
var page = UIPageControl(frame: CGRectMake(0, 0, scroll.frame.size.width, scroll.frame.size.height))
page.numberOfPages = arrayImage.count
page.currentPage = 0
page.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
scroll.contentSize = CGSizeMake(scroll.frame.size.width * CGFloat(arrayImage.count - 1) , 0)
scroll.delegate = self
scroll.pagingEnabled = true
scroll.maximumZoomScale = 6
scroll.minimumZoomScale = 0.5
scroll.tag = Tags.Tag_MainScroll.rawValue
scroll.addSubview(page)
view.addSubview(scroll)
scroll.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
scroll.contentOffset = CGPointMake(scroll.frame.size.width * CGFloat(index - 1) , 0)
}
//MARK: Display Selected Image
func displayImage()
{
var mainScroll : UIScrollView = view.viewWithTag(Tags.Tag_MainScroll.rawValue) as UIScrollView
var arrayImage = NSUserDefaults.standardUserDefaults().objectForKey("ImageArray") as NSMutableArray
var xPosition : CGFloat = 0
for i in 1...22
{
var subScroll = UIScrollView(frame: CGRectMake(xPosition, 0, view.frame.size.width, view.frame.size.height))
subScroll.delegate = self
subScroll.maximumZoomScale = 6
subScroll.minimumZoomScale = 0.5
subScroll.tag = Tags.Tag_SubScroll.rawValue + i
mainScroll.addSubview(subScroll)
var imgToDisplay : UIImage = UIImage(named: "\(arrayImage[i])")! as UIImage
var imgView : UIImageView = UIImageView(frame: CGRectMake((subScroll.frame.size.width - 100 ) / 2,(subScroll.frame.size.height - 100) / 2, 100, 100))
subScroll.contentSize = CGSizeMake(imgView.frame.size.width, imgView.frame.size.height)
imgView.image = imgToDisplay
imgView.tag = Tags.Tag_imgView.rawValue
subScroll.addSubview(imgView)
xPosition += subScroll.frame.size.width
}
}
Here Is my Delete Function...
func Delete()
{
var imgView : UIImageView? = view.viewWithTag(Tags.Tag_imgView.rawValue) as? UIImageView
var scroll : UIScrollView = view.viewWithTag(Tags.Tag_MainScroll.rawValue) as UIScrollView
for img in scroll.subviews
{
imgView = img as? UIImageView
imgView?.removeFromSuperview()
}
}`
have u tryed this one..
let subViews = self.scrollView.subviews
for subview in subViews{
subview.removeFromSuperview()
}
HERE is the reference
as per my code this Delete Function is working for me
func Delete()
{
var imgView : UIImageView? = view.viewWithTag(Tags.Tag_imgView.rawValue) as? UIImageView
var scroll : UIScrollView = view.viewWithTag(Tags.Tag_MainScroll.rawValue) as UIScrollView
var number : Int = Int(scroll.contentOffset.x / scroll.frame.size.width)
var page : UIPageControl = view.viewWithTag(Tags.Tag_page.rawValue) as UIPageControl
page.currentPage = number
println("\(page.currentPage)")
if var array : NSArray = NSUserDefaults.standardUserDefaults().objectForKey("ImageArray") as? NSArray
{
arrayImage = array.mutableCopy() as NSMutableArray
}
page.removeFromSuperview()
number++
arrayImage.removeObjectAtIndex(number)
NSUserDefaults.standardUserDefaults() .setObject(arrayImage, forKey: "ImageArray")
println("\(arrayImage[number])")
println("\(arrayImage)")
NSUserDefaults.standardUserDefaults().synchronize()
displayImage()
}