Xcode scrollview not working - ios

I'm making a game and need users to sign an End User License Agreement (EULA). The EULA is long and requires a scroll view. I want the screen itself to stay still, so the buttons and header are always present:
Here is a screenshot of my viewController storyboard:
here's my code:
#IBOutlet var eulaView: UIView!
#IBOutlet var scrollView: UIScrollView!
#IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let width = eulaView.frame.width
let height = eulaView.frame.height
self.scrollView.frame = CGRect(x: 0, y: 0, width: width, height: height)
self.label.frame = CGRect(x: 0, y: 0, width: width , height: 2000)
self.label.text = "Lots of stuff"
}
Strangely, if I set self.label.frame's width to 100, it shows up. If I have it at 300, or "width", the label disappears.
No matter what, the scroll view doesn't scroll.
PS: I had it working earlier, but then I tried it on an iPhone X simulator and it was blank.

You need to set self.scrollView.contentSize = CGSize(width: width,height: 2000)
Sometimes When you change device in storyboard at that time screen was blank may be its bug of xcode.
To find the Dynamic Height Of label Depends on String Of label.
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}

Related

Auto-sizing a UILabel without setting an explicit height

How do I get a multi-line label to size itself? I don't want to set an explicit height for it but I do need to place it in view.
The way my app is built, we explicitly set frames and origins rather than using NSLayoutConstraints. It's a mature app so this isn't up for discussion.
I'd like to be able to give my UILabel an origin and a width and let it figure its own height out.
How can I do this? This is my playground code:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 180))
view.backgroundColor = .white
let l = UILabel()
l.text = "this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno"
l.textColor = .black
l.lineBreakMode = .byWordWrapping
l.numberOfLines = 0
l.textAlignment = .center
l.sizeToFit()
let margin: CGFloat = 60
view
view.addSubview(l)
l.frame = CGRect(x: margin, y: 0, width: view.bounds.width - (margin * 2), height: 100)
// I don't want to do this ^^
This may do what you want...
As requested, you want to set the .origin and .width of a UILabel and have it set its own .height based on the text.
class ZackLabel: UILabel {
override public func layoutSubviews() {
super.layoutSubviews()
let h = sizeThatFits(CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude))
self.frame.size.height = h.height
}
}
class ViewController: UIViewController {
var testLabel: ZackLabel!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
// instantiate a 300 x 180 UIView at 20, 80
let myView = UIView(frame: CGRect(x: 20, y: 80, width: 300, height: 180))
myView.backgroundColor = .white
// instantiate a ZackLabel
testLabel = ZackLabel()
testLabel.text = "this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno"
testLabel.textColor = .black
testLabel.lineBreakMode = .byWordWrapping
testLabel.numberOfLines = 0
testLabel.textAlignment = .center
// set background color so we can see its frame
testLabel.backgroundColor = .cyan
let margin: CGFloat = 60
// set label's origin
testLabel.frame.origin = CGPoint(x: margin, y: 0)
// set label's width (label will set its own height)
testLabel.frame.size.width = myView.bounds.width - margin * 2
// add the view
view.addSubview(myView)
// add the label to the view
myView.addSubview(testLabel)
// add a tap recognizer so we can change the label's text at run-time
let rec = UITapGestureRecognizer(target: self, action: #selector(tapFunc(_:)))
view.addGestureRecognizer(rec)
}
#objc func tapFunc(_ sender: UITapGestureRecognizer) -> Void {
testLabel.text = "This is dynamic text being set."
}
}
Result (on an iPhone 8):
and, after tapping on the (yellow) view, dynamically changing the text:
label.sizeThatFits(CGSize(width: <your required width>, height: CGFloat.greatestFiniteMagnitude))
This returns the labels needed size, growing infinitely in height, but fitted to your required width. I've occasionally noticed minor inaccuracies with this function (rounding error?), so I tend to bump the width and height by 1 just to be safe.
UILabel comes with an intrinsic size that should be calculated based on the text and the label's .font property. You may need to add a margin to it...
var height = l.intrinsicContentSize.height
height += margin
l.frame = CGRect(x: margin, y: 0, width: view.bounds.width - (margin * 2), height: height)
Failing that, maybe you can try something like:
let size = CGSize(width: view.bounds.width - (margin * 2), height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
var estimatedFrame = CGRect()
if let font = l.font {
estimatedFrame = NSString(string: l.text).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: font], context: nil)
}
//if you need a margin:
estimatedFrame.height += margin
l.frame = estimatedFrame
Give your UILabel as a UIScrollview or UITableView cell subview.
Then you setup UILabel leading, tralling, top, bottom constrain.
If you give UITableview then set table view hight auto dynamic. If you give UIScrollview
just set UILabel bottom constrain priority low

How can I update a UIView width with a UISlider?

I'm trying to change the width of a UIView with a slider. My problem is that instead of updating the views width my code is adding new views. I don't know how to update the view with swift playgrounds.
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
var feelings01Slider: UISlider!
var feelingsWidth01 = 100
var dayFeelings01: UIView!
var dayFeelings02: UIView!
var dayFeelings03: UIView!
override func loadView() {
let view = UIView()
view.backgroundColor = .white
self.view = view
feelings01Slider = UISlider()
feelings01Slider.frame = CGRect(x: 62, y: 375, width: 250, height: 20)
feelings01Slider.minimumValue = 1
feelings01Slider.maximumValue = 248
feelings01Slider.value = 100
feelings01Slider.isContinuous = true
feelings01Slider.addTarget(self, action: #selector(sliderValueDidChange(sender:)), for: .valueChanged)
setUpFeelings()
view.addSubview(feelings01Slider)
}
func setUpFeelings() {
feelingsWidth01 = Int(feelings01Slider.value)
var feelingsX02 = feelingsWidth01 + 62
var feelingsWidth02 = 80
var feelingsX03 = feelingsX02 + feelingsWidth02
var feelingsWidth03 = 70
dayFeelings01 = UIView(frame: CGRect(x: 62, y: 100, width: feelingsWidth01, height: 250))
dayFeelings01.backgroundColor = .yellow
dayFeelings02 = UIView(frame: CGRect(x: feelingsX02, y: 100, width: feelingsWidth02, height: 250))
dayFeelings02.backgroundColor = .blue
dayFeelings03 = UIView(frame: CGRect(x: feelingsX03, y: 100, width: feelingsWidth03, height: 250))
dayFeelings03.backgroundColor = .red
view.addSubview(dayFeelings01)
view.addSubview(dayFeelings02)
view.addSubview(dayFeelings03)
}
#objc func sliderValueDidChange(sender:UISlider) {
feelingsWidth01 = Int(sender.value)
dayFeelings03.removeFromSuperview()
dayFeelings02.removeFromSuperview()
dayFeelings01.removeFromSuperview()
setUpFeelings()
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
I'm new to programming so excuse me if my code seems messy.
You don't need to replace the views with new, differently-sized views . You can just change their frames. Replace your slider selector action with this:
#objc func sliderValueDidChange(sender:UISlider) {
dayFeelings01.frame.size.width = CGFloat(sender.value)
}
Note: because the yellow view was added first, it is expanding underneath the other views. That's why you can't see it get wider. Try changing the order so it's added last and you'll see it. If you want the other views to adjust to the available space, you can update their frames too, a UIStackView might make that easy.
Good luck!

Programmatically display UIScrollView in Swift

I have view controller with views: top level View Contains Container View which contains two views: bottomView, topView, as shown.
Scene
I want to display from: to: date range in the topView. In the bottomView I want to display a UIScrollView that contains two columns which I can scroll. I did that but the topView and BottomView overlap when I introduce scrollView. When I scroll I can see the views getting separated and as soon as i Let go the scrollbar they overlap again.
can someone tell me how to fix it? I just don't seem to understand how the scrollView and bottomView are to be associated.
Code below:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
//scrollView.frame = innerView.bounds
innerView.frame = CGRect(x:0, y:0, width:scrollView.contentSize.width, height:scrollView.contentSize.height)
}
func buildBottomView () {
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let ht:Int = 21
let incrX:Int = 5
let incrY:Int = 5
let gapCol1:Int = 5
let col1Width:Int = 65
let col2Width:Int = 65
let startY:Int = 5
let col1StartX:Int = 10
let col2StartX:Int = col1StartX + col1Width + gapCol1
var loadRowStartY: Int = 0
// column headers
categoryColumnLabel.text = "Interval"
categoryColumnLabel.font = UIFont.preferredFont(forTextStyle:UIFontTextStyle.subheadline)
//categoryColumnLabel.font = UIFont.systemFont(ofSize: 14)
categoryColumnLabel.frame = CGRect(x: col1StartX, y:startY, width: col1Width, height: ht)
categoryColumnLabel.textAlignment = NSTextAlignment.left
categoryColumnLabel.tag = 1
innerView.addSubview(categoryColumnLabel)
valueColumnLabel.text = "Values"
valueColumnLabel.font = UIFont.preferredFont(forTextStyle:UIFontTextStyle.subheadline)
//valueColumnLabel.font = UIFont.systemFont(ofSize: 14)
valueColumnLabel.frame = CGRect(x: col2StartX, y:startY, width: col2Width, height: ht)
valueColumnLabel.textAlignment = NSTextAlignment.center
valueColumnLabel.tag = 3
innerView.addSubview(valueColumnLabel)
let sepLine:UIView = UIView()
sepLine.frame = CGRect(x: col1StartX, y:startY+ht+incrY, width: Int(screenWidth-20), height: 2)
sepLine.backgroundColor = UIColor.darkGray
sepLine.tag = 60
loadRowStartY = startY+ht+incrX+ht
innerView.addSubview(sepLine)
for i in 0 ..< 24 {
let timeIntervalLabel = UILabel()
let value2Label = UILabel()
print("display load profile")
let loadStruct = loadDict[String(i)] as! CommercialProfile
print (loadStruct.timeInterval)
timeIntervalLabel.text = loadStruct.timeInterval
timeIntervalLabel.font = UIFont.preferredFont(forTextStyle:UIFontTextStyle.caption1)
//valueColumnLabel.font = UIFont.systemFont(ofSize: 14)
timeIntervalLabel.frame = CGRect(x: col1StartX, y:loadRowStartY, width: col1Width, height: Int(timeIntervalLabel.font.lineHeight))
timeIntervalLabel.textAlignment = NSTextAlignment.center
innerView.addSubview(timeIntervalLabel)
print(loadStruct.value)
value2Label.text = loadStruct.value
value2Label.font = UIFont.preferredFont(forTextStyle:UIFontTextStyle.caption1)
//value2Label = UIFont.systemFont(ofSize: 14)
value2Label.frame = CGRect(x: col2StartX, y:loadRowStartY, width: col2Width, height: Int(value2Label.font.lineHeight))
value2Label.textAlignment = NSTextAlignment.center
innerView.addSubview(value2Label)
loadRowStartY = loadRowStartY + incrY + Int(value2Label.font.lineHeight)
}
you are setting the bounds of the scrollView to the size of the whole view with this code: scrollView.frame = view.bounds.
The scrollView only needs to scroll the content in the bottom view. Scroll Views have their own content, that is normally larger than the viewable area of the screen/view. The scroll view just allows you to pan the viewport of that view.
So add the bottom view and setup your constraints on that. add the scrollView to the bottom view and then add your content into the scrollView.
Make sure that your bottom view has clipToBounds set to true and then you should be able to keep the headers in place and just scroll the content.
I'll try and put an example together for you shortly.
EDIT:
I've just created this simple example which shows the scroll behaviour you need. This works in a playground or just as a simple view controller. I've intentionally not used auto layout or setup constraints due to time, but you will see what you need to solve your issue
class ViewController: UIViewController {
var topView: UIView!
var bottomView: UIView!
var scrollView: UIScrollView!
var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let screenSize = UIScreen.main.bounds
self.topView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: 100))
self.bottomView = UIView(frame: CGRect(x: 0, y: 100, width: screenSize.width, height: screenSize.height - 100))
self.scrollView = UIScrollView(frame: CGRect(x: 0, y: 100, width: screenSize.width, height: screenSize.height - 100))
self.contentView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height * 3))
self.view.backgroundColor = .white
self.view.addSubview(self.topView)
self.view.addSubview(self.bottomView)
self.bottomView.addSubview(self.scrollView)
self.scrollView.addSubview(self.contentView)
self.bottomView.clipsToBounds = true
self.scrollView.contentSize = CGSize(width: screenSize.width, height: screenSize.height * 3)
self.contentView.backgroundColor = .gray
}
}

Make UIView fill UIScrollview

I have a paging scrollview with two views, and the first one is to fill the UIScrollview and the second to stay in the middle. I don't know what's going wrong, but it wouldn't fill on iPhone6 but, it fits fine on iPhone5. Below is my code:
View Hierarchy
UIView
--StackView (Properties -- Axis(Vertical) Alignment(Fill) Distribution(Fill) Spacing(0))
--UIView (Fixed height. 60)
--UIView (Main Views Holder)
--ScrollView(Content Size: Screen Width * 2, Height: Height left between it margin to the MainView and BottomView) and I notice, that the scrollview keeps remaining size 433 on both iPhone5 and 6. And when I check my storyboard, that's the exact same height there
--UIView(Height: 102, Width: Screen Width)BottomView
#IBOutlet weak var scrollView: UIScrollView!
var rectanglePhot: UIView!
var squarePhoto: UIView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize = CGSize(width: self.view.frame.size.width * 2, height: scrollView.frame.size.height)
scrollView.autoresizingMask = .FlexibleWidth
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.backgroundColor = UIColor.greenColor()
iniiCameraView()
}
func iniiCameraView() {
rectanglePhot = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.scrollView.frame.size.height)) <-- This is the problematic one
//rectanglePhot = UIView()
let specifyY = self.scrollView.frame.size.height - self.view.frame.size.width
squarePhoto = UIView(frame: CGRect(x: self.view.frame.size.width, y: specifyY, width: self.view.frame.size.width, height: self.view.frame.size.width))
scrollView.addSubview(rectanglePhot)
scrollView.addSubview(squarePhoto)
rectanglePhot.backgroundColor = UIColor.blueColor()
squarePhoto.backgroundColor = UIColor.brownColor()
print("Rect Height ", rectanglePhot.frame.size.height)
print("Scroll Height ", scrollView.frame.size.height)
print("Specify Y ", specifyY)
}
And the image Image Added to Scrollview a index[0]
Add the code in viewdidappear. The autolayout will be applied after viewdidload
Replace
UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.scrollView.frame.size.height))
With :
UIView(frame: CGRect(x: 0, y: 0, width: self.scrollView.bounds.size.width, height: self.scrollView.bounds.size.height))
With this the UIView will take the exact size of you scrollview
if you don't want to use autolayout: add subviews in viewDidLoad, that is fine but you also need to adjust their frames in viewDidLayoutSubviews method of UIViewController since your scrollView will have a different frame after autolayout passes.
if you are ok with using autolayout: don't rely on scrollView for sizing your subviews, relate size of your subviews to the size of self.view

UILabel not visible in circular custom UIView

My view hierarchy looks like the following, I have a UITableViewController -> Static Cells -> UITableViewCell -> Custom UIView -> UILabel
My goal is to show circular profile image views and the last view shows a count with the number of remaining images.
That's how I create a circular view which works perfectly fine
private func getCircularViewForPoint(point: CGPoint) -> UIView {
var circularView: UIView = UIView(frame: CGRect(x: point.x, y: point.y, width: 30, height: 30))
circularView.layer.cornerRadius = 15
circularView.layer.masksToBounds = true
circularView.backgroundColor = UIColor.blueColor()
return circularView
}
So now I want to create such a view with a UILabel inside
private func getCircularCountViewForPoint(point: CGPoint, maxAmount: Int) -> UIView {
var circularView = self.getCircularViewForPoint(point)
circularView.backgroundColor = UIColor.brownColor()
var label: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
label.center = circularView.center
label.text = "XY"
label.font = UIFont.systemFontOfSize(10.0)
label.textAlignment = NSTextAlignment.Center
// self.addSubview(label) // This works but label is now behind circularView of course
circularView.addSubview(label)
return circularView
}
The outcome looks like this, with no UILabel in the brown view.
Frame of circularView:
<UIView: 0x7feb28fd9d50; frame = (295 24.75; 30 30); clipsToBounds = YES; ...
Frame of label:
<UILabel: 0x7feb28ce33b0; frame = (295 24.75; 30 30); userInteractionEnabled = NO; ...
The weird thing is, if I put this code into a playground, it works like expected and the label is visible.
Just for completeness that's how I call these two functions
for var i = 0; i < maxAmount-1; i++ {
self.addSubview(self.getCircularViewForPoint(CGPoint(x: xPos, y: yPos)))
xPos += size+offset
}
// add count view
var countView = self.getCircularCountViewForPoint(CGPoint(x: xPos, y: yPos), maxAmount: maxAmount)
self.addSubview(countView)
since your goal is to show profile pictures i would have tried to replace the brown background with the picture:
circularView.backgroundColor = UIColor(patternImage: UIImage(named: "profilepicturename.png")!)
sorry i couldn't help with the label thing

Resources