How to change the height of the UISegmentedControl? [duplicate] - ios

This question already has answers here:
iOS: change the height of UISegmentedcontrol
(16 answers)
Closed 3 years ago.
I am using an UISegmentedControl in an UITableView as follows-
let segmentedControl = UISegmentedControl(items: ["Segment1", "Segment2"])
tableView.tableHeaderView = segmentedControl
The above code works as expected. I would like to change the height of the UISegmentedControl. I tried to set a height constraint on the UISegmentedControl as follows-
let segmentedControl = UISegmentedControl(items: ["Segment1", "Segment2"])
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.heightAnchor.constraint(equalToConstant: 50).isActive = true
tableView.tableHeaderView = segmentedControl
When the above code is run, the height of the UISegmentedControl is set to the expected custom height. However, the leading and trailing edges of the UISegmentedControl do not snap to the leading and trailing edges of the UITableView.
I also tried to create a custom UISegmentedControl to specify the height of the UISegmentedControl without setting a height constraint as follows-
class CustomSegmentedControl: UISegmentedControl {
override var intrinsicContentSize: CGSize {
return CGSize(width: super.intrinsicContentSize.width, height: 50)
}
}
The above code does not work as expected. Can anyone point out how to set the height of the UISegmentedControl so that it appears as expcted when used in UITableView?

By setting segmentedControl.translatesAutoresizingMaskIntoConstraints = false you're losing the default constraints.
If you are happy with the appearance and layout of the segmented control, you just want to change its height, try this approach:
// probably in
override func viewDidLoad() {
super.viewDidLoad()
let segmentedControl = UISegmentedControl(items: ["Segment1", "Segment2"])
segmentedControl.frame.size.height = 50.0
tableView.tableHeaderView = segmentedControl
}

Same question as this:
iOS: change the height of UISegmentedcontrol
By the way, you can also change the scale by changing views transform.
var segmentedControl = UISegmentedControl(frame: CGRect(x: 0, y: 0, width: w, height: h))
segmentedControl.transform = CGAffineTransform(scaleX: x, y: y)

Just set the frame to tableView.tableHeaderView. Don't use constraints.
tableView.tableHeaderView?.frame.size.height = 50

Related

Swift - Adjust size on separator of UITableViewCell

I have at problem with my cells in a UITableView. I have used the Attribute Inspector to adjust the size. Like this:
But the adjustment only applied on the cells with content. How do I make the separator to be the same size for the whole tableview using Swift or the Attribute Inspector?
For your question, you can try this
tableView.tableFooterView = UIView()
Another way you can do like this.
Then,
In cellForRowAtIndexPath
tableView.separatorStyle = .none
let horizontalGap = 15.0 as CGFloat
// As you want to have equal gaping in left & right side, you have to position the view's origin.x to the constant and have to have the width minus the double of that constant.
let seperatorView = UIView(frame: CGRect(x: horizontalGap, y: cell.frame.size.height - 1, width: cell.frame.size.width - horizontalGap * 2.0, height: 1))
seperatorView.backgroundColor = UIColor.red
cell.addSubview(seperatorView)
In Storyboard
Change Separator as None in Attributes Inspector. Drag UIView and place it inside your cell . Give constraints like, Leading 15, Trailing 15, Bottom 0 and height 1. Change background color to red

UIScrollView didn't scroll

I've some problem with ScrollView.
I'm trying to create a scrollview and add to it dynamically some buttons.
So i create a scrollView in my main storyboard with some constraints. (0 to left, 0 to right, 0 to botton and 1/10 height).
Now, i want to add some button.
#IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
for index in 0..<12 {
let frame1 = CGRect(x: 0 + (index * 60), y: 0, width: 45, height: 45 )
let button = UIButton(frame: frame1)
button.setTitle("toto", forState: .Normal)
button.backgroundColor = UIColor.green()
scrollView.addSubview(button)
}
}
So now the problem is : my buttons are present but i can't scroll. The scroll is enabled in the storyBoard. I tried to enabled it in the code but nothing changed..
set the contentSize of your scrollView
self. scrollView.contentSize = CGSizeMake(required_width, required_height)
for example
self. scrollView.contentSize = CGSizeMake(500, 74) // custtomize ur self
You have to set the contentSize of the scrollView
The height to set is probably the origin.y + the size.height of the last button.
use this code to set scrollview height
scrollview.contentInset = UIEdgeInsetsMake(0, 0, 50, 0)
//50 is the height of scroll view you can change it to the height you want
scrollview.bounces = false
or you can also change content inset from here
by changing the values of content inset (height or width)

Scrollview ContentSize

I am trying to make a scrollview with 3 pictures on a sign up/join page for a small app I trying to make. I was using this code below:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var signInButton: UIButton!
var joinButton: UIButton!
var pageControl: UIPageControl!
#IBOutlet weak var scrollView: UIScrollView!
var colors:[UIColor] = [UIColor.redColor(), UIColor.blueColor(), UIColor.greenColor(), UIColor.yellowColor()]
var frame = CGRectMake(0, 0, 0, 0)
override func viewDidLoad() {
super.viewDidLoad()
signInButton = UIButton(frame: CGRectMake(1/3.0 * self.view.bounds.size.width, 5/6.0 * self.view.bounds.size.height, 23, 60))
joinButton = UIButton(frame: CGRectMake(2/3.0 * self.view.bounds.size.width, 5/6.0 * self.view.bounds.size.height, 23, 60))
pageControl = UIPageControl(frame: CGRectMake(1/2.0 * self.view.bounds.size.width, 70/100.0 * self.view.bounds.size.height, 23, 60))
self.view.addSubview(signInButton)
self.view.addSubview(joinButton)
self.view.addSubview(pageControl)
signInButton.addTarget(self, action: "signInButtonClicked:", forControlEvents: .TouchUpInside)
joinButton.addTarget(self, action: "joinButtonClicked:", forControlEvents: .TouchUpInside)
pageControl.addTarget(self, action: Selector("changePage:"), forControlEvents: UIControlEvents.ValueChanged)
configurePageControl()
scrollView.delegate = self
for index in 0...3 {
frame.size = scrollView.frame.size
frame.origin.x = scrollView.frame.size.width * CGFloat(index)
scrollView.pagingEnabled = true
let view: UIView = UIView(frame: frame)
view.backgroundColor = colors[index]
scrollView.addSubview(view)
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * 4, self.scrollView.frame.size.height)
}
func configurePageControl() {
self.pageControl.numberOfPages = colors.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.redColor()
self.pageControl.pageIndicatorTintColor = UIColor.blackColor()
self.pageControl.currentPageIndicatorTintColor = UIColor.greenColor()
}
I put a scrollview on my view controller (using the size class width: Any and height: Any) and pinned all four sides of the scrollview to the view controller. For some reason each of the views I add to the scrollview are not exactly the same width as the iPhone.
For example when, I tried running it on an iPhone 6 the first view extends past the width of the iPhone. And that happens to the second and third view. I want the first view to be the exact width of the iPhone and the second view to be exactly to the right of the first view and so on. There seems to be some overlapping with the first view going past the width of the iPhone.
Could this be because I am using the size class (width: any and height: any) and I should disable size classes and add a scrollview for each iPhone width?
Can someone help me identify the problem here.
Add:
scrollView.setNeedsLayout()
scrollView.layoutIfNeeded()
at the beginning of the viewDidLoad() method.
Always call these two methods before accessing a view's frame when using Auto Layout, otherwise you'll probably get an incorrect size.
The problem is that when viewDidLoad() is called, your view still has a width of 600 (due to your storyboard view controller size of 600x600).
Your constraints dictate that the scroll view should be the same width as the device, but these constraints are only applied after viewDidLoad() finishes, when Auto Layout's next scheduled pass is calculated.
Adding the code above forces Auto Layout to perform a pass, thus giving you the correct frame sizes for subsequent use in your size calculations.
Put your scroll view in , set your constraint. Then grab a UIView, put it IN the scroll view, set it as equal width, equal height, and center it (use CTRL + drag to the scroll view, you'll get a small pop up menu)
Then put your content in the UIView you just created... Bam ! also I personally rename my UIView to ContentView, just for sake
Here's a screen to help :
Now I myself am still having issue with the height, I usually simply use a fixed height for the content view because if I don't it doesn't scroll....

Creating a grey space between the header view and the first cell

I am trying to create a grey space between the header view (with the two buttons) and the dynamic tableview as shown here:
This is what I was able to create so far:
Now there is a line between the header view and the dynamic table view. However, I would like to have a grey space as shown in the picture above. I tried using Grouped instead of Plain. And I hypothesize that this is a way to achieve my goal because it does add grey to my view like so but only at the bottom:
So I figured if I can add some padding unto my headerview, that cause the grey to show since I think the background is grey now. So I tried writing some code:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let headerView = taskListTableView.tableHeaderView
headerView!.setNeedsLayout()
headerView!.layoutIfNeeded()
let cGPoint = CGPoint(x: 0.0, y: 0.0)
let cGHeight = CGSize.init(width: 0, height: 10)
var frame = headerView!.frame
headerView!.bounds = CGRect(origin: cGpoint, size: cGHeight)
frame.size.height = CGFloat(30.0)
headerView!.frame = frame
taskListTableView.tableHeaderView = headerView
}
But this code is won't compile. Am I on the right track? What else could I do to achieve this effect?

How do I set adaptive multiline UILabel text?

I have a UILabel named titleLabel in my storyboard nib set to its default height. I want it to programatically expand in height to fit it's content. Here is what I have tried so far:
// just setting content
titleLabel.text = "You don't always know what you are getting with mass-market cloud computing services. But with SimpliCompute, the picture is clear. SimpliCompute gives you powerful virtual servers you can deploy using just your web browser. That’s enterprise grade technology you can deploy and control on-the-fly."
titleLabel.numberOfLines = 0
titleLabel.preferredMaxLayoutWidth = 700
titleLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
titleLabel.sizeToFit()
None of this works for me in any combination! I always only see one line of text in my UILabel. What am I doing wrong?
I absolutely need the text content to be variable.
I kind of got things working by adding auto layout constraints:
But I am not happy with this. Took a lot of trial and error and couldn't understand why this worked.
Also I had to add to use titleLabel.numberOfLines = 0 in my ViewController
I know it's a bit old but since I recently looked into it :
let l = UILabel()
l.numberOfLines = 0
l.lineBreakMode = .ByWordWrapping
l.text = "BLAH BLAH BLAH BLAH BLAH"
l.frame.size.width = 300
l.sizeToFit()
First set the numberOfLines property to 0 so that the device understands you don't care how many lines it needs.
Then specify your favorite BreakMode
Then the width needs to be set before sizeToFit() method. Then the label knows it must fit in the specified width
This is much better approach if you are looking for multiline dynamic text label which exactly takes the space based on its text.
No sizeToFit, preferredMaxLayoutWidth used
Below is how it will work.
Lets set up the project. Take a Single View application and in Storyboard Add a UILabel and a UIButton. Define constraints to UILabel as below snapshot:
Set the Label properties as below image:
Add the constraints to the UIButton. Make sure that vertical spacing of 100 is between UILabel and UIButton
Now set the priority of the trailing constraint of UILabel as 749
Now set the Horizontal Content Hugging and Horizontal Content Compression properties of UILabel as 750 and 748
Below is my controller class. You have to connect UILabel property and Button action from storyboard to viewcontroller class.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textLabel: UILabel!
var count = 0
let items = ["jackson is not any more in this world", "Jonny jonny yes papa eating sugar no papa", "Ab", "What you do is what will happen to you despite of all measures taken to reverse the phenonmenon of the nature"]
#IBAction func updateLabelText(sender: UIButton) {
if count > 3 {
count = 0
}
textLabel.text = items[count]
count = count + 1
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.textLabel.sizeToFit()
//self.textLabel.preferredMaxLayoutWidth = 500
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thats it. This will automatically resize the UILabel based on its content and also you can see the UIButton is also adjusted accordingly.
It should work. Try this
var label:UILabel = UILabel(frame: CGRectMake(10
,100, 300, 40));
label.textAlignment = NSTextAlignment.Center;
label.numberOfLines = 0;
label.font = UIFont.systemFontOfSize(16.0);
label.text = "First label\nsecond line";
self.view.addSubview(label);
With Graphical User Interface (GUI) in Xcode, you can do the following:
Go to "Attribute Inspector" and set Lines value to 0. By default, it is set to 1.
The Label text can be written in multi-line by hitting option + return.
Now, go to "Size Inspector" and set the width, height, X & Y position of the Label.
That's all.
Programmatically, Swift
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.titleView.numberOfLines = 2
Programmatically in Swift 5 with Xcode 10.2
Building on top of #La masse's solution, but using autolayout to support rotation
Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)
label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()
If setting frame.width dynamically using UIScreen:
extension UIScreen { // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
class func absoluteWidth() -> CGFloat {
var width: CGFloat
if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
width = self.main.bounds.height // Landscape
} else {
width = self.main.bounds.width // Portrait
}
return width
}
}
extension UILabel {
var textSize: CGSize { text?.size(withAttributes: [.font: font!]) ?? .zero }
func setSizeForText(_ str: String, maxWidth: CGFloat) {
text = str
let dividedByMaxWidth = Int(textSize.width / maxWidth)
if dividedByMaxWidth == 0 {
frame.size = textSize
} else {
numberOfLines = dividedByMaxWidth + 1
frame.size = CGSize(width: maxWidth, height: frame.size.height * CGFloat(numberOfLines))
sizeToFit()
}
}
}
sizeToFit() in the end will shrink the label's width to the widest line after word break
This has worked for me:
Set the numberOfLines property of UILabel to 0
add this line: yourLabel.sizeToFit() after assigning text to the UILabel

Resources