So I know there are a couple of post like mine, but not quite what I am looking for. So here is what I am trying to accomplish. I have this ViewController that looks like this.
When a user inputs text into the UITextView, which currently has the text "Description", I want to dynamically change the height of the UITextView so if the text where to become multiple lines or go off screen the user can scroll through the whole view with its contents. Here is my program.
#IBOutlet var scrollView: UIScrollView!
var projectNameTextField: UITextField!
var projectCategoryLabel: UIButton!
var dueDateLabel: UIButton!
var projectDescription: UITextView!
var projectDescriptionFrame: CGRect!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let scrollViewWidth = scrollView.frame.width
scrollView.contentSize.width = scrollViewWidth
let trallingSpace: CGFloat = 12.0
let contentWidth = scrollViewWidth - (trallingSpace * 2.0)
projectNameTextField = UITextField(frame: CGRect(x: trallingSpace, y: scrollViewContentHeight(), width: contentWidth, height: 40))
projectNameTextField.placeholder = "Title"
updateScrollView(withView: projectNameTextField)
let categoryLabel = UILabel()
categoryLabel.text = "Category"
projectCategoryLabel = UIButton()
projectCategoryLabel.setTitle("Art", forState: .Normal)
projectCategoryLabel.setTitleColor(UIColor.blackColor(), forState: .Normal)
let stackViewHCategory = UIStackView(frame: CGRect(x: trallingSpace, y: scrollViewContentHeight(), width: contentWidth, height: 40))
stackViewHCategory.axis = .Horizontal
stackViewHCategory.spacing = 8
stackViewHCategory.addArrangedSubview(categoryLabel)
stackViewHCategory.addArrangedSubview(projectCategoryLabel)
updateScrollView(withView: stackViewHCategory)
let dueDateTitle = UILabel()
dueDateTitle.text = "Due Date"
dueDateLabel = UIButton()
dueDateLabel.setTitle("No Due Date", forState: .Normal)
dueDateLabel.setTitleColor(UIColor.blackColor(), forState: .Normal)
let stackViewHDueDate = UIStackView(frame: CGRect(x: trallingSpace, y: scrollViewContentHeight(), width: contentWidth, height: 40))
stackViewHDueDate.axis = .Horizontal
stackViewHDueDate.spacing = 8
stackViewHDueDate.addArrangedSubview(dueDateTitle)
stackViewHDueDate.addArrangedSubview(dueDateLabel)
updateScrollView(withView: stackViewHDueDate)
projectDescription = UITextView(frame: CGRect(x: trallingSpace, y: scrollViewContentHeight(), width: contentWidth, height: 40))
projectDescription.text = "Description"
projectDescription.delegate = self
projectDescription.scrollEnabled = false
projectDescription.font = projectDescription.font?.fontWithSize(14)
updateScrollView(withView: projectDescription)
projectDescriptionFrame = projectDescription.frame
projectDescriptionFrame.size.height = projectDescription.contentSize.height
projectDescription.frame = projectDescriptionFrame
}
func textViewDidChange(textView: UITextView) {
projectDescriptionFrame.size.height = projectDescription.contentSize.height
projectDescription.frame = projectDescriptionFrame
var contentSizeheight = CGFloat()
for (index, viewInScrollView) in scrollView.subviews.enumerate() {
if index > 1 {
contentSizeheight += viewInScrollView.frame.height
}
}
scrollView.contentSize.height = contentSizeheight
}
func updateScrollView(withView withView: UIView) {
scrollView.addSubview(withView)
scrollView.contentSize.height += withView.frame.height
}
func scrollViewContentHeight() -> CGFloat {
var height = CGFloat()
for (index, viewInScrollView) in scrollView.subviews.enumerate() {
if index > 1 {
height += viewInScrollView.frame.height
}
}
return height
}
How can I do this so that it will adjust the UITextView frame and update the UIScrollView.contentSize (Not of UITextView) so then the user can scroll through the whole view. And I would say I want a UI like when you make a new message in iOS Mail app. There you are able to scroll through the emails subject and the body of the message as one. Please help me with this. I have been stuck on this for days.
Okay I figured it out. Here is what I changed.
In the global properties.
var oldProjectDescriptionHeight: CGFloat!
var projectDescriptionHeight: CGFloat! {
willSet {
oldProjectDescriptionHeight = projectDescriptionHeight
}
}
And in the UITextViewDelegate textViewDidChange
func textViewDidChange(textView: UITextView) {
let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame
projectDescriptionHeight = newFrame.height
scrollView.contentSize.height += projectDescriptionHeight - oldProjectDescriptionHeight
}
Related
I want horizontal scrollview with image view but image is not fitting with the scroll. i am doing this code but not getting the right thing
Here is my code
#IBOutlet weak var upperScroll: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
// Do any additional setup after loading the view.
var logoImage: [UIImage] = [
UIImage(named: "slider.png")!,
UIImage(named: "slider.png")!,
UIImage(named: "slider.png")!,
UIImage(named: "slider.png")!,
]
upperScroll.isScrollEnabled = true
let scrollWidth: Int = Int(self.view.frame.width)
upperScroll.contentSize = CGSize(width: CGFloat(scrollWidth), height:(self.upperScroll.frame.height))
upperScroll.frame = CGRect(x: 0, y: 51, width: upperScroll.frame.size.width, height: self.upperScroll.frame.height)
upperScroll.backgroundColor = UIColor.red
var xOffset: Int = 0
for index in 0..<logoImage.count {
let img = UIImageView(frame: CGRect(x: CGFloat(xOffset), y: 0, width: upperScroll.frame.size.width, height: self.upperScroll.frame.height))
img.image = logoImage[index]
upperScroll.addSubview(img)
xOffset += 100
}
view.addSubview(upperScroll)
upperScroll.contentSize = CGSize(width: CGFloat((scrollWidth + xOffset)), height: 110)
}
but i want this
Can anyone please help me? Thanks
Just remove your appdelegate code and add my fuction
also set scrollview constraint like leading,trailing,top,bottom Zero
func scrollImage() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
// Do any additional setup after loading the view.
var logoImage: [UIImage] = [
UIImage(named: "slider.png")!,
UIImage(named: "slider.png")!,
UIImage(named: "slider.png")!,
UIImage(named: "slider.png")!]
upperScroll.isPagingEnabled = true
upperScroll.isScrollEnabled = true
let scrollWidth: Int = Int(self.view.frame.width)
,
upperScroll.contentSize = CGSize(width: CGFloat(scrollWidth), height:(self.upperScroll.frame.height))
print(upperScroll.frame.size.width)
upperScroll.backgroundColor = UIColor.red
for index in 0..<logoImage.count {
let xPosition = self.view.frame.width * CGFloat(index)
upperScroll.layoutIfNeeded()
let img = UIImageView(frame: CGRect(x: CGFloat(xPosition), y: 0, width: upperScroll.frame.size.width, height: self.upperScroll.frame.height))
img.layoutIfNeeded()
img.image = logoImage[index]
upperScroll.addSubview(img)
}
view.addSubview(upperScroll)
upperScroll.contentSize = CGSize(width: CGFloat((scrollWidth) * logoImage.count), height: self.upperScroll.frame.height)
}
I hope it's save your time and working great
According to your requirement, the xOffset += 100 should be changed to xOffset += scrollWidth. And contents size set to:
upperScroll.contentSize = CGSize(width: CGFloat((scrollWidth * logoImage.count)), height: 110)
And remember to enable the pagination for scroll view.
First of all, you need two outlet for scroll view and PageControl,
var contentWidth:CGFloat = 0.0
// MARK: - Welcome screen with scroll view use page controll
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
scrollView.delegate = self
let myImages = ["intro1_1.png", "intro2_2.png", "intro3_3.png"] // images which loaded in assets
let imageWidth:CGFloat = view.frame.width
let imageHeight:CGFloat = view.frame.height
var xPosition:CGFloat = 0 //setup your position
var scrollViewSize:CGFloat=0 //setup your position
for image in myImages {
let myImage:UIImage = UIImage(named: image)!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.frame.size.width = imageWidth
myImageView.frame.size.height = imageHeight
myImageView.frame.origin.x = xPosition
myImageView.frame.origin.y = 0
scrollView.addSubview(myImageView)
xPosition += imageWidth
scrollViewSize += imageWidth
}
scrollView.contentSize = CGSize(width: scrollViewSize, height: imageHeight)
scrollView.contentSize = CGSize(width: view.frame.width * 3, height: view.frame.height) //here you setup how many pages in scroll will
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageWidth:CGFloat = scrollView.frame.width
let currentPage:CGFloat = floor((scrollView.contentOffset.x-pageWidth / 2)/pageWidth)+1
self.pageControll.currentPage = Int(currentPage)
}
hope, i help u
im kinda new to the programming world specifically on swift.
Ive started to practice a bit and im currently working on a demo app just to explore..
So right now what the app suppose to do is to show have a scroll view, and each screen shows a different "animal" or any other subject by an Image, a Label and an Icon, on the side theres a slider with 1-5 values which suppose to show how much you "love" that subject on a scale of 1 to 5.
everything works except I cant seem to add a label to each of the screens above the slider to show its current value.
with the current code it shows every screen with its appropriate image/label/icon, shows the right Page on the page indicator, and shows a working Slider,
only on the last frame the Slider have a Label that is connected to its value.
cant seem to figure it out
hopefully its clear enough, thanks alot.
(P.S Im fully aware that i might be doing this thing completely wrong in the first place, enlighten me its welcome)
class ViewController: UIViewController, UIScrollViewDelegate {
public var sliderLbl = UILabel()
#IBOutlet var mainScrollView: UIScrollView!
#IBOutlet var secondScrollView: UIScrollView!
var imageArray = [UIImage]()
var iconImg = [UIImage]()
var pageControl : UIPageControl = UIPageControl(frame: CGRect(x: 160, y: 420, width: 50, height: 100))
var subjects:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mainScrollView.delegate = self
mainScrollView.frame = view.frame
imageArray = [pic1.png, pic2.png, pic3.png, pic4.png, pic5.png]
subjects = ["Dog", "Cat", "Mouse", "Cow", "Snake"]
iconImg = [icon1.png, icon2.png, icon3.png, icon4.png]
for i in 0..<imageArray.count{
let labelView = UILabel()
let imageView = UIImageView()
let subjIcon = UIImageView()
let oneSlider = UISlider()
let sliderLabel = sliderLbl
sliderLabel.textColor = UIColor.black
oneSlider.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))
oneSlider.minimumValue = 1
oneSlider.maximumValue = 5
oneSlider.isUserInteractionEnabled = true
oneSlider.value = 1
oneSlider.tintColor = UIColor.darkGray
oneSlider.isContinuous = true
sliderLabel.text = "1"
labelView.text = subjects[i]
labelView.textColor = UIColor.darkGray
labelView.textAlignment = .center
imageView.alpha = 0.85
imageView.image = imageArray[i]
imageView.contentMode = .center
subjIcon.image = iconImg[i]
subjIcon.contentMode = .scaleAspectFit
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: -50, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)
labelView.frame = CGRect(x: xPosition, y: -250, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)
iconImg.frame = CGRect(x: xPosition, y: 500, width: self.mainScrollView.frame.width, height: 150)
oneSlider.frame = CGRect(x: xPosition, y: 250, width: 50, height: 130)
sliderLabel.frame = CGRect(x: xPosition+20, y: 180, width: self.mainScrollView.frame.width, height: 80)
mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)
// Add subViews
mainScrollView.addSubview(subjIcon)
mainScrollView.addSubview(imageView)
mainScrollView.addSubview(labelView)
mainScrollView.bringSubview(toFront: subjIcon)
oneSlider.addTarget(self, action: #selector(sliderSlid(_:)) ,for: UIControlEvents.valueChanged)
mainScrollView.addSubview(sliderLabel)
mainScrollView.addSubview(oneSlider)
func configurePageControl() {
self.pageControl.numberOfPages = imageArray.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.lightGray
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
configurePageControl()
}
}
func sliderSlid(_ sender: UISlider) {
sliderLbl.text = String(Int(roundf(sender.value)))
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(mainScrollView.contentOffset.x / mainScrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Hi I am trying to make a game using swift but am currently very stuck. My game has two buttons that move a UIImageView left and right which works perfectly although when my NSTimer calls to my animateBalls function every 2.5 seconds the UIImageView that was moved goes back to its original position. How would I be able to still be able to create a New UIView every 2.5 seconds but keep the UIIMageViews current position? Thanks for any help that you can give me, Here is my code:
import UIKit
class ViewController: UIViewController {
let speed = 10.0
#IBOutlet weak var mainBar: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
_ = NSTimer.scheduledTimerWithTimeInterval(2.5, target: self, selector: Selector("animateBalls"), userInfo: nil, repeats: true)
}
#IBAction func moveRightIsTapped(sender: AnyObject) {
if(mainBar.frame.origin.x < -158.5)
{
let xPosition = mainBar.frame.origin.x + 38.5
let yPosition = mainBar.frame.origin.y
let height = mainBar.frame.height
let width = mainBar.frame.width
mainBar.frame = CGRectMake(xPosition, yPosition, width, height)
}
}
#IBAction func moveLeftIsTapped(sender: AnyObject) {
if(mainBar.frame.origin.x > -389.5)
{
let xPosition = mainBar.frame.origin.x - 38.5
let yPosition = mainBar.frame.origin.y
let height = mainBar.frame.height
let width = mainBar.frame.width
mainBar.frame = CGRectMake(xPosition, yPosition, width, height)
}
}
#IBAction func playButtonTapped(sender: AnyObject) {
animateBalls()
}
func animateBalls() {
randomNum = Int(arc4random_uniform(1))
if(randomNum == 0)
{
let ball1 = UIView()
ball1.frame = CGRect(x: 121, y: -20, width: 20, height: 20)
ball1.layer.cornerRadius = 10
ball1.clipsToBounds = true
ball1.backgroundColor = UIColor.purpleColor()
self.view.addSubview(ball1)
UIView.animateWithDuration(speed, animations:{ ball1.frame = CGRect(x: 121, y: 705, width: ball1.frame.width, height: ball1.frame.height) })
}
if(randomNum == 1)
{
let ball2 = UIView()
ball2.frame = CGRect(x: 159, y: -20, width: 20, height: 20)
ball2.layer.cornerRadius = 10
ball2.clipsToBounds = true
ball2.backgroundColor = UIColor.greenColor()
self.view.addSubview(ball2)
UIView.animateWithDuration(speed, animations:{ ball2.frame = CGRect(x: 159, y: 705, width: ball2.frame.width, height: ball2.frame.height) })
}
I am a beginner. I am unable to solve the following problem:
I would like to place a lot of buttons in a page. These buttons must appear in small size, but must have a possibility to zoom in for clicking on these items. I tried the following without success:
class myViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let myArray =
[["O","1","2","3","4","5","6","7","8","9","10","11","12"],
["1","2","3","4","5","6","7","8","9","10","11","12","13"],
["1","2","3","4","5","6","7","8","9","10","11","12","13"],
["1","2","3","4","5","6","7","8","9","10","11","12","13"]]
var buttonY: CGFloat = 50
for index in 0...myArray.count-1 {
buttonY = buttonY + 45
var buttonX: CGFloat = 10
for (index2, myArraytxt) in myArray[index].enumerate() {
let myButton = UIButton(frame: CGRect(x: buttonX, y: buttonY, width: 30, height: 30))
buttonX = buttonX + 40
myButton.backgroundColor = UIColor.greenColor()
myButton.setTitle(myArraytxt, forState: UIControlState.Normal)
myButton.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)
}
self.scrollView.addSubview(myButton)
}
self.scrollView.minimumZoomScale = 0.4
self.scrollView.maximumZoomScale = 3.0
self.scrollView.zoomScale = 0.4
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.view
}
}
Any help or idea is appreciated!
Regards: Zoltan
How can i implement UIScrollView when swiping snap to its subviews width. I need it to behave like pagingEnabled but i cant enable paging because i need my entire view can be swipe to scroll. if i do pagingEnable its impossible because scrollview bounds will be change to subviews width.
is there any possible way to do this.
please check the image for more details
import UIKit
class ViewController: UIViewController{
var navigationScroller: UIScrollView!
var contentScroller: UIScrollView!
var navContainer: UIView!
var contentContainer: UIView!
var selfWidth:CGFloat?
var navigationLabels = ["EVENTS", "MEMBERS", "SECTORS", "ORGANIZATIONS", "SEARCH", "EVENTS", "MEMBERS"]
private var buttonsTextFontAndSize: UIFont = UIFont(name: "HelveticaNeue-Light", size: 14)!
override func viewDidLoad() {
super.viewDidLoad()
selfWidth = self.view.frame.width
let frameWidth = self.view.frame.width
let frameHeight = self.view.frame.height
//let navscrollPosition = CGFloat( (frameWidth/2) - (75.0/2) )
navContainer = UIView(frame: CGRectMake(0.0, 75.0, frameWidth, 40.0))
navContainer.backgroundColor = UIColor(red:0, green:0.302, blue:0.522, alpha:1)
navigationScroller = UIScrollView(frame: CGRectMake(0.0, 0.0, frameWidth, 40.0))
navigationScroller.backgroundColor = UIColor.clearColor()
navigationScroller.pagingEnabled = false
navigationScroller.showsHorizontalScrollIndicator = false
navigationScroller.showsVerticalScrollIndicator = false
navigationScroller.clipsToBounds = false
navigationScroller.contentInset = UIEdgeInsetsZero
//navigationScroller.userInteractionEnabled = false
//navigationScroller.
addNavigationLabels(navigationScroller)
self.view.addSubview(navContainer)
navContainer.addSubview(navigationScroller)
navigationScroller.contentSize = CGSize(width: 150.0 * CGFloat(navigationLabels.count),height: 40.0)
navigationScroller.contentOffset = CGPoint(x: 170.0, y:0.0)
contentContainer = UIView(frame: CGRectMake(0.0, 115.0, frameWidth, frameHeight-115.0))
contentContainer.backgroundColor = UIColor.clearColor()
contentScroller = UIScrollView(frame: CGRectMake(0.0, 0.0, frameWidth, frameHeight-115.0))
contentScroller.backgroundColor = UIColor.clearColor()
contentScroller.pagingEnabled = true
contentScroller.showsHorizontalScrollIndicator = false
contentScroller.showsVerticalScrollIndicator = false
contentScroller.clipsToBounds = true
contentScroller.contentInset = UIEdgeInsetsZero
//contentScroller.addSubview(navContainer)
addContents(contentScroller)
self.view.addSubview(contentContainer)
contentContainer.addSubview(contentScroller)
contentScroller.contentSize = CGSize(width: frameWidth * CGFloat(navigationLabels.count),
height: frameHeight-115.0)
//contentScroller.delegate = self
navigationScroller.delegate = self
}
//MARK: -View Appeared function
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: -Adding navigation labels fron navigation labels array
private func addNavigationLabels(navScrollView:UIScrollView){
var buttonsXPosition: CGFloat = 0
var buttonNumber = 0
for navLabel in navigationLabels {
var navButton: UIButton!
let red = CGFloat(buttonNumber) - 0.9
let frameWidth = self.view.frame.width
navButton = UIButton(frame: CGRectMake(buttonsXPosition, 0, frameWidth/3, 40.0))
navButton.titleLabel!.font = buttonsTextFontAndSize
navButton.contentHorizontalAlignment = .Center
navButton.backgroundColor = UIColor(red:red , green:0.114, blue:0.286, alpha:1)
navButton.setTitle(navLabel, forState: UIControlState.Normal)
navButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
navScrollView.addSubview(navButton)
buttonsXPosition = frameWidth/3 + buttonsXPosition
buttonNumber++
}
}
func buttonAction(sender:UIButton!){
print("pressed")
}
// MARK: -Adding navigation labels fron navigation labels array
private func addContents(contentScroller:UIScrollView){
var buttonsXPosition: CGFloat = 0
var buttonNumber = 0
let frameWidth = self.view.frame.width
let frameHeight = self.view.frame.height
for navLabel in navigationLabels {
var navButton: UIButton!
navButton = UIButton(frame: CGRectMake(buttonsXPosition, 40.0, frameWidth, frameHeight-155))
navButton.titleLabel!.font = buttonsTextFontAndSize
navButton.contentHorizontalAlignment = .Center
navButton.backgroundColor = UIColor.darkGrayColor()
navButton.setTitle(navLabel, forState: UIControlState.Normal)
contentScroller.addSubview(navButton)
buttonsXPosition = frameWidth + buttonsXPosition
buttonNumber++
}
}
}
app view
You can implement UIScrollViewDelegate's method scrollViewWillEndDragging:withVelocity:targetContentOffset: and modify the offset at it will finish decelerating to match the width that you wish.
Something like this:
class ScrollSample: NSObject, UIScrollViewDelegate {
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let targetOffset = targetContentOffset.memory.x
// Round the offset to be a multiple of scrollview width
let roundedOffset = round(targetOffset / scrollView.frame.width) * scrollView.frame.width
targetContentOffset.memory = CGPoint(x: roundedOffset, y: 0)
}
}