Label next to a label with variable length The 2019 Stack Overflow Developer Survey Results Are InVariable length label, tableview row heights, and auto layoutUsing Auto Layout in UITableView for dynamic cell layouts & variable row heightsUIScrollView Scrollable Content Size Ambiguityhow to scroll tableview after inserting a row at the bottom correctly?Update labels in UITableViewCell from multiple threadsUIScrollView + Centered View + Ambigous Scrollable Content Size + many iPhone sizesScrollView -> View (Label + Label + TableView) and autolayoutiOS horizontal UIStackView with 3 labels - First label pushed other labels out of sightHow to implement TableView inside CollectionView programaticallyUpdating Label in Cell
What is the motivation for a law requiring 2 parties to consent for recording a conversation
Button changing its text & action. Good or terrible?
Why can't devices on different VLANs, but on the same subnet, communicate?
Correct punctuation for showing a character's confusion
What do I do when my TA workload is more than expected?
How do I free up internal storage if I don't have any apps downloaded?
Why didn't the Event Horizon Telescope team mention Sagittarius A*?
Will it cause any balance problems to have PCs level up and gain the benefits of a long rest mid-fight?
How to obtain a position of last non-zero element
Did the UK government pay "millions and millions of dollars" to try to snag Julian Assange?
Geography at the pixel level
Can an undergraduate be advised by a professor who is very far away?
Unitary representations of finite groups over finite fields
What is preventing me from simply constructing a hash that's lower than the current target?
Keeping a retro style to sci-fi spaceships?
Why are there uneven bright areas in this photo of black hole?
How do PCB vias affect signal quality?
Can a flute soloist sit?
Does adding complexity mean a more secure cipher?
Worn-tile Scrabble
"as much details as you can remember"
How to translate "being like"?
Why don't hard Brexiteers insist on a hard border to prevent illegal immigration after Brexit?
Are there any other methods to apply to solving simultaneous equations?
Label next to a label with variable length
The 2019 Stack Overflow Developer Survey Results Are InVariable length label, tableview row heights, and auto layoutUsing Auto Layout in UITableView for dynamic cell layouts & variable row heightsUIScrollView Scrollable Content Size Ambiguityhow to scroll tableview after inserting a row at the bottom correctly?Update labels in UITableViewCell from multiple threadsUIScrollView + Centered View + Ambigous Scrollable Content Size + many iPhone sizesScrollView -> View (Label + Label + TableView) and autolayoutiOS horizontal UIStackView with 3 labels - First label pushed other labels out of sightHow to implement TableView inside CollectionView programaticallyUpdating Label in Cell
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I would like to have tableview's row which contains two labels. First will contains a name which can be different length and the second one will contain a number in brackets. For example :
|Example Name (8) |
|Example very very long name (10)|
|Exmaple very very very very... (21)|
|Name (6) |
|Example name name name n...(2)|
Rows with dots should be scrollable. Second label should be always next to first one but if first is too long second label should still be visible on the screen and first should be horizontally scrollable.
Using DonMag's solution:
It almost work. I get views that I wanted but left label is not scrollable. It has dots at the end and I can't see the rest part of label.
My tableview:
Constraints:
Right label:
Scroll View:
ios
add a comment |
I would like to have tableview's row which contains two labels. First will contains a name which can be different length and the second one will contain a number in brackets. For example :
|Example Name (8) |
|Example very very long name (10)|
|Exmaple very very very very... (21)|
|Name (6) |
|Example name name name n...(2)|
Rows with dots should be scrollable. Second label should be always next to first one but if first is too long second label should still be visible on the screen and first should be horizontally scrollable.
Using DonMag's solution:
It almost work. I get views that I wanted but left label is not scrollable. It has dots at the end and I can't see the rest part of label.
My tableview:
Constraints:
Right label:
Scroll View:
ios
Have you tried setting content hugging priority for both the labels ? High value of hugging priority will take the priority and expand the intrinsic size.
– Bharath Vankireddy
Mar 8 at 11:26
I have added Label1's settings to my question. This settings doesn't work.
– matekome
Mar 8 at 12:05
@matekome - not quite clear what you're trying to do. If your labels are (L1
) "abc" and (L2
) "123456789", you want it displayed withL1
followed by a small space thenL2
followed by a large space to the edge of the view? And asL1
has more text, it pushesL2
to the right, untilL2
hits the edge and thenL1
scrolls? Or do you want it to start as in your image, withL2
always at the right edge?
– DonMag
Mar 8 at 13:22
I have extended my example. Please look at my edited question.
– matekome
Mar 8 at 13:45
add a comment |
I would like to have tableview's row which contains two labels. First will contains a name which can be different length and the second one will contain a number in brackets. For example :
|Example Name (8) |
|Example very very long name (10)|
|Exmaple very very very very... (21)|
|Name (6) |
|Example name name name n...(2)|
Rows with dots should be scrollable. Second label should be always next to first one but if first is too long second label should still be visible on the screen and first should be horizontally scrollable.
Using DonMag's solution:
It almost work. I get views that I wanted but left label is not scrollable. It has dots at the end and I can't see the rest part of label.
My tableview:
Constraints:
Right label:
Scroll View:
ios
I would like to have tableview's row which contains two labels. First will contains a name which can be different length and the second one will contain a number in brackets. For example :
|Example Name (8) |
|Example very very long name (10)|
|Exmaple very very very very... (21)|
|Name (6) |
|Example name name name n...(2)|
Rows with dots should be scrollable. Second label should be always next to first one but if first is too long second label should still be visible on the screen and first should be horizontally scrollable.
Using DonMag's solution:
It almost work. I get views that I wanted but left label is not scrollable. It has dots at the end and I can't see the rest part of label.
My tableview:
Constraints:
Right label:
Scroll View:
ios
ios
edited Mar 9 at 14:25
matekome
asked Mar 8 at 11:07
matekomematekome
34
34
Have you tried setting content hugging priority for both the labels ? High value of hugging priority will take the priority and expand the intrinsic size.
– Bharath Vankireddy
Mar 8 at 11:26
I have added Label1's settings to my question. This settings doesn't work.
– matekome
Mar 8 at 12:05
@matekome - not quite clear what you're trying to do. If your labels are (L1
) "abc" and (L2
) "123456789", you want it displayed withL1
followed by a small space thenL2
followed by a large space to the edge of the view? And asL1
has more text, it pushesL2
to the right, untilL2
hits the edge and thenL1
scrolls? Or do you want it to start as in your image, withL2
always at the right edge?
– DonMag
Mar 8 at 13:22
I have extended my example. Please look at my edited question.
– matekome
Mar 8 at 13:45
add a comment |
Have you tried setting content hugging priority for both the labels ? High value of hugging priority will take the priority and expand the intrinsic size.
– Bharath Vankireddy
Mar 8 at 11:26
I have added Label1's settings to my question. This settings doesn't work.
– matekome
Mar 8 at 12:05
@matekome - not quite clear what you're trying to do. If your labels are (L1
) "abc" and (L2
) "123456789", you want it displayed withL1
followed by a small space thenL2
followed by a large space to the edge of the view? And asL1
has more text, it pushesL2
to the right, untilL2
hits the edge and thenL1
scrolls? Or do you want it to start as in your image, withL2
always at the right edge?
– DonMag
Mar 8 at 13:22
I have extended my example. Please look at my edited question.
– matekome
Mar 8 at 13:45
Have you tried setting content hugging priority for both the labels ? High value of hugging priority will take the priority and expand the intrinsic size.
– Bharath Vankireddy
Mar 8 at 11:26
Have you tried setting content hugging priority for both the labels ? High value of hugging priority will take the priority and expand the intrinsic size.
– Bharath Vankireddy
Mar 8 at 11:26
I have added Label1's settings to my question. This settings doesn't work.
– matekome
Mar 8 at 12:05
I have added Label1's settings to my question. This settings doesn't work.
– matekome
Mar 8 at 12:05
@matekome - not quite clear what you're trying to do. If your labels are (
L1
) "abc" and (L2
) "123456789", you want it displayed with L1
followed by a small space then L2
followed by a large space to the edge of the view? And as L1
has more text, it pushes L2
to the right, until L2
hits the edge and then L1
scrolls? Or do you want it to start as in your image, with L2
always at the right edge?– DonMag
Mar 8 at 13:22
@matekome - not quite clear what you're trying to do. If your labels are (
L1
) "abc" and (L2
) "123456789", you want it displayed with L1
followed by a small space then L2
followed by a large space to the edge of the view? And as L1
has more text, it pushes L2
to the right, until L2
hits the edge and then L1
scrolls? Or do you want it to start as in your image, with L2
always at the right edge?– DonMag
Mar 8 at 13:22
I have extended my example. Please look at my edited question.
– matekome
Mar 8 at 13:45
I have extended my example. Please look at my edited question.
– matekome
Mar 8 at 13:45
add a comment |
2 Answers
2
active
oldest
votes
A little tricky, but not too tricky...
What you need to do is set multiple, similar constraints and use a combination of Content Compression Resistance Priority
and Constraint Priority
on the different elements.
Take a look at this:
- We embed Left Label in a scroll view.
- We constrain the width of the scroll view to the width of the label, but with a Priority of
750
. That will allow the scroll view to expand (and contract) with the label until it can't expand anymore. - We add constraints to Right Label... leading to the scroll view, and trailing to the right edge of the view, with the trailing set to
>= 20
and the compression resistance set to1000
. That allows the label to "stick" to the scroll view as it expands / contracts, but will not allow it to go past the right edge, nor compress past its own content width. - The rest of the constraints are pretty standard.
And we get:
I whipped up a simple example that will let you change the text with button taps to see it in action:
Here's the class:
class ScrollingLabelViewController: UIViewController
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
override func viewDidLoad()
super.viewDidLoad()
@IBAction func leftTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
leftLabel.text = "Example Name"
case "Medium Text":
leftLabel.text = "Example Longer Name"
case "Long Text":
fallthrough
default:
leftLabel.text = "Example Name that is long enough that it will need to scroll."
@IBAction func rightTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
rightLabel.text = "(6)"
case "Medium Text":
rightLabel.text = "(255)"
case "Long Text":
fallthrough
default:
rightLabel.text = "(38,872)"
And the Storyboard source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="itP-Si-dAD">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Scrolling Label View Controller-->
<scene sceneID="2HK-o9-I65">
<objects>
<viewController id="itP-Si-dAD" customClass="ScrollingLabelViewController" customModule="XC10SWScratch" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="C9r-ad-Wv2">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Rs3-TC-hFe">
<rect key="frame" x="20" y="60" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="3jj-Oq-9XF">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="3jj-Oq-9XF" secondAttribute="bottom" id="7EF-mm-DaK"/>
<constraint firstAttribute="width" secondItem="3jj-Oq-9XF" secondAttribute="width" priority="750" id="ZtX-rP-Lme"/>
<constraint firstAttribute="width" relation="greaterThanOrEqual" constant="12" id="ZyU-il-ReF"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="top" id="ml2-6X-bBl"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="leading" id="r4q-LE-OQ5"/>
<constraint firstAttribute="trailing" secondItem="3jj-Oq-9XF" secondAttribute="trailing" id="t9q-89-BOF"/>
<constraint firstAttribute="height" secondItem="3jj-Oq-9XF" secondAttribute="height" id="xDp-np-bFT"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ZCj-c5-IzQ">
<rect key="frame" x="142.5" y="60" width="23" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<stackView opaque="NO" contentMode="scaleToFill" spacing="47" translatesAutoresizingMaskIntoConstraints="NO" id="0v3-eY-MTM">
<rect key="frame" x="44" y="160.5" width="287" height="164.5"/>
<subviews>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="nou-P9-haw">
<rect key="frame" x="0.0" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Left Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Jgc-gS-1Oz">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mPG-zF-zdi">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="z5m-yd-ACM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="xiv-Uc-UPL">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="hCp-75-WVo"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="LQD-gc-Pv1">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="fWI-cl-wGZ"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="Mvo-co-QSU"/>
</constraints>
</stackView>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="usT-YQ-P4a">
<rect key="frame" x="167" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Right Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="WXA-Lo-BaW">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="UXZ-r3-dw1">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="1e8-Dh-iHD"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="BN2-Tt-2QG">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="8CM-Gx-TYM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="vCy-ut-LXL">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="iTb-4n-jbd"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="ACw-Tb-RfF"/>
</constraints>
</stackView>
</subviews>
</stackView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="leading" secondItem="N2s-Cz-Yp4" secondAttribute="leading" constant="20" id="Dkw-df-pKY"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="centerY" secondItem="Rs3-TC-hFe" secondAttribute="centerY" id="GsG-U4-jc6"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="trailing" constant="8" id="aVZ-i7-91I"/>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="top" secondItem="N2s-Cz-Yp4" secondAttribute="top" constant="40" id="jFX-1U-cRh"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="centerX" secondItem="C9r-ad-Wv2" secondAttribute="centerX" id="jZO-qZ-0z5"/>
<constraint firstItem="N2s-Cz-Yp4" firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="ZCj-c5-IzQ" secondAttribute="trailing" constant="20" id="pP1-gC-Uvq"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="bottom" constant="80" id="sJi-4A-BOA"/>
</constraints>
<viewLayoutGuide key="safeArea" id="N2s-Cz-Yp4"/>
</view>
<connections>
<outlet property="leftLabel" destination="3jj-Oq-9XF" id="469-ke-ni2"/>
<outlet property="rightLabel" destination="ZCj-c5-IzQ" id="hMG-sN-B29"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="w9F-EF-F89" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="167" y="1506"/>
</scene>
</scenes>
</document>
Edit: pretty much the same thing, but setup as a XIB for use as a table view cell.
ScrollingLabelCell.xib
in IB:
ScrollingLabelCell.xib
source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" id="SVi-M2-eJO" customClass="ScrollingLabelCell" customModule="XC10SWScratch" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="SVi-M2-eJO" id="FO6-8m-8lR">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="1TD-My-nqW" userLabel="Inner View">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="fPZ-Vc-pTX">
<rect key="frame" x="16" y="11.5" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Gsx-qe-uXG">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="Gsx-qe-uXG" secondAttribute="bottom" id="KNJ-P5-R1c"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="top" secondItem="fPZ-Vc-pTX" secondAttribute="top" id="M63-Na-FHd"/>
<constraint firstAttribute="height" secondItem="Gsx-qe-uXG" secondAttribute="height" id="kQb-o9-Cmr"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="leading" id="od5-IF-Drl"/>
<constraint firstAttribute="trailing" secondItem="Gsx-qe-uXG" secondAttribute="trailing" id="pVh-95-8bc"/>
<constraint firstAttribute="width" secondItem="Gsx-qe-uXG" secondAttribute="width" priority="750" id="zUu-pN-rme"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="cnK-Pa-DDF">
<rect key="frame" x="142.5" y="11.5" width="23" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="leading" secondItem="1TD-My-nqW" secondAttribute="leading" constant="16" id="24S-Dy-Pf7"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="cnK-Pa-DDF" secondAttribute="trailing" constant="20" id="9P7-Or-S8M"/>
<constraint firstAttribute="bottom" secondItem="fPZ-Vc-pTX" secondAttribute="bottom" constant="11.5" id="BD3-7Z-Ry9"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="centerY" secondItem="fPZ-Vc-pTX" secondAttribute="centerY" id="Q4G-6M-3Qe"/>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="top" secondItem="1TD-My-nqW" secondAttribute="top" constant="11.5" id="lOh-MF-Khj"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="trailing" constant="12" id="mVz-me-wRN"/>
</constraints>
</view>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="1TD-My-nqW" secondAttribute="bottom" id="fgL-GE-OC3"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="leading" secondItem="FO6-8m-8lR" secondAttribute="leading" id="iV5-qZ-Oq7"/>
<constraint firstAttribute="trailing" secondItem="1TD-My-nqW" secondAttribute="trailing" id="whk-Ke-oc7"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="top" secondItem="FO6-8m-8lR" secondAttribute="top" id="yIU-Lz-jlC"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="leftLabel" destination="Gsx-qe-uXG" id="9kR-67-2oC"/>
<outlet property="rightLabel" destination="cnK-Pa-DDF" id="p4k-MJ-gb2"/>
</connections>
<point key="canvasLocation" x="156" y="50.374812593703155"/>
</tableViewCell>
</objects>
</document>
and example cell and table view controller classes:
class ScrollingLabelCell: UITableViewCell
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
class ScrollingLabelTableViewController: UITableViewController
let xibName = "ScrollingLabelCell"
let theData: [[String]] = [
["Example Name", "1"],
["Example Longer Name", "2"],
["Example Even Longer Name", "3"],
["To demonstrate the scrolling,", "4"],
["6, 7 & 800 have the same name", "5"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "6"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "7"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "800"],
["Back to Short Names", "99"],
["With longer numbers", "2,750"],
]
override func viewDidLoad()
super.viewDidLoad()
let bundle = Bundle(for: type(of: self))
let cellNib = UINib(nibName: xibName, bundle: bundle)
tableView.register(cellNib, forCellReuseIdentifier: xibName)
override func numberOfSections(in tableView: UITableView) -> Int
return 1
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return theData.count
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: xibName, for: indexPath) as! ScrollingLabelCell
cell.leftLabel.text = theData[indexPath.row][0]
cell.rightLabel.text = "(" + theData[indexPath.row][1] + ")"
return cell
I almost work. Please look at my edited question.
– matekome
Mar 9 at 14:26
Did you try using the code and Storyboard that I posted? Because that worked for me, including scrolling the left label (see the screen cap). If you're getting truncated instead of scrolling, I suspect you're missing a constraint / setting.
– DonMag
Mar 9 at 14:55
@matekome - see my edited answer
– DonMag
Mar 11 at 13:09
add a comment |
You can accomplish this either with constraints, or you can try playing around with stackViews, since this is generally their intended use:
UIStackview
| Label 1 | UIScrollView (Label 2) |
In this case, just add the width constraint to the scrollView
to be >= than your intended size and increase the vertical priority for the label 1
.
I would also reconsider against having the label inside a scrollView, inside another scrollView (your tableView in this specific case) since it will be pretty janky to get something that small to scroll. Probably better to just consider placing the labels one underneath the other or some other layout improvement requiring less tweaking and having a better UX.
I'm not sure you understood me well. First label should be scrollable if is too long. So i will scroll something which is not too small to scroll. I only whant want twol labels next to each other in one row but second label should be always visible. I don't want second label be out of the screen so if first label is too long it should be scrollable but second one should be still on the screen.
– matekome
Mar 8 at 12:15
The principle is still the same, wherever the scrollView is.
– Adis
Mar 8 at 15:02
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55061924%2flabel-next-to-a-label-with-variable-length%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
A little tricky, but not too tricky...
What you need to do is set multiple, similar constraints and use a combination of Content Compression Resistance Priority
and Constraint Priority
on the different elements.
Take a look at this:
- We embed Left Label in a scroll view.
- We constrain the width of the scroll view to the width of the label, but with a Priority of
750
. That will allow the scroll view to expand (and contract) with the label until it can't expand anymore. - We add constraints to Right Label... leading to the scroll view, and trailing to the right edge of the view, with the trailing set to
>= 20
and the compression resistance set to1000
. That allows the label to "stick" to the scroll view as it expands / contracts, but will not allow it to go past the right edge, nor compress past its own content width. - The rest of the constraints are pretty standard.
And we get:
I whipped up a simple example that will let you change the text with button taps to see it in action:
Here's the class:
class ScrollingLabelViewController: UIViewController
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
override func viewDidLoad()
super.viewDidLoad()
@IBAction func leftTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
leftLabel.text = "Example Name"
case "Medium Text":
leftLabel.text = "Example Longer Name"
case "Long Text":
fallthrough
default:
leftLabel.text = "Example Name that is long enough that it will need to scroll."
@IBAction func rightTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
rightLabel.text = "(6)"
case "Medium Text":
rightLabel.text = "(255)"
case "Long Text":
fallthrough
default:
rightLabel.text = "(38,872)"
And the Storyboard source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="itP-Si-dAD">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Scrolling Label View Controller-->
<scene sceneID="2HK-o9-I65">
<objects>
<viewController id="itP-Si-dAD" customClass="ScrollingLabelViewController" customModule="XC10SWScratch" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="C9r-ad-Wv2">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Rs3-TC-hFe">
<rect key="frame" x="20" y="60" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="3jj-Oq-9XF">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="3jj-Oq-9XF" secondAttribute="bottom" id="7EF-mm-DaK"/>
<constraint firstAttribute="width" secondItem="3jj-Oq-9XF" secondAttribute="width" priority="750" id="ZtX-rP-Lme"/>
<constraint firstAttribute="width" relation="greaterThanOrEqual" constant="12" id="ZyU-il-ReF"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="top" id="ml2-6X-bBl"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="leading" id="r4q-LE-OQ5"/>
<constraint firstAttribute="trailing" secondItem="3jj-Oq-9XF" secondAttribute="trailing" id="t9q-89-BOF"/>
<constraint firstAttribute="height" secondItem="3jj-Oq-9XF" secondAttribute="height" id="xDp-np-bFT"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ZCj-c5-IzQ">
<rect key="frame" x="142.5" y="60" width="23" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<stackView opaque="NO" contentMode="scaleToFill" spacing="47" translatesAutoresizingMaskIntoConstraints="NO" id="0v3-eY-MTM">
<rect key="frame" x="44" y="160.5" width="287" height="164.5"/>
<subviews>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="nou-P9-haw">
<rect key="frame" x="0.0" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Left Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Jgc-gS-1Oz">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mPG-zF-zdi">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="z5m-yd-ACM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="xiv-Uc-UPL">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="hCp-75-WVo"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="LQD-gc-Pv1">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="fWI-cl-wGZ"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="Mvo-co-QSU"/>
</constraints>
</stackView>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="usT-YQ-P4a">
<rect key="frame" x="167" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Right Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="WXA-Lo-BaW">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="UXZ-r3-dw1">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="1e8-Dh-iHD"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="BN2-Tt-2QG">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="8CM-Gx-TYM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="vCy-ut-LXL">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="iTb-4n-jbd"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="ACw-Tb-RfF"/>
</constraints>
</stackView>
</subviews>
</stackView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="leading" secondItem="N2s-Cz-Yp4" secondAttribute="leading" constant="20" id="Dkw-df-pKY"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="centerY" secondItem="Rs3-TC-hFe" secondAttribute="centerY" id="GsG-U4-jc6"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="trailing" constant="8" id="aVZ-i7-91I"/>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="top" secondItem="N2s-Cz-Yp4" secondAttribute="top" constant="40" id="jFX-1U-cRh"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="centerX" secondItem="C9r-ad-Wv2" secondAttribute="centerX" id="jZO-qZ-0z5"/>
<constraint firstItem="N2s-Cz-Yp4" firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="ZCj-c5-IzQ" secondAttribute="trailing" constant="20" id="pP1-gC-Uvq"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="bottom" constant="80" id="sJi-4A-BOA"/>
</constraints>
<viewLayoutGuide key="safeArea" id="N2s-Cz-Yp4"/>
</view>
<connections>
<outlet property="leftLabel" destination="3jj-Oq-9XF" id="469-ke-ni2"/>
<outlet property="rightLabel" destination="ZCj-c5-IzQ" id="hMG-sN-B29"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="w9F-EF-F89" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="167" y="1506"/>
</scene>
</scenes>
</document>
Edit: pretty much the same thing, but setup as a XIB for use as a table view cell.
ScrollingLabelCell.xib
in IB:
ScrollingLabelCell.xib
source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" id="SVi-M2-eJO" customClass="ScrollingLabelCell" customModule="XC10SWScratch" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="SVi-M2-eJO" id="FO6-8m-8lR">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="1TD-My-nqW" userLabel="Inner View">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="fPZ-Vc-pTX">
<rect key="frame" x="16" y="11.5" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Gsx-qe-uXG">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="Gsx-qe-uXG" secondAttribute="bottom" id="KNJ-P5-R1c"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="top" secondItem="fPZ-Vc-pTX" secondAttribute="top" id="M63-Na-FHd"/>
<constraint firstAttribute="height" secondItem="Gsx-qe-uXG" secondAttribute="height" id="kQb-o9-Cmr"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="leading" id="od5-IF-Drl"/>
<constraint firstAttribute="trailing" secondItem="Gsx-qe-uXG" secondAttribute="trailing" id="pVh-95-8bc"/>
<constraint firstAttribute="width" secondItem="Gsx-qe-uXG" secondAttribute="width" priority="750" id="zUu-pN-rme"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="cnK-Pa-DDF">
<rect key="frame" x="142.5" y="11.5" width="23" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="leading" secondItem="1TD-My-nqW" secondAttribute="leading" constant="16" id="24S-Dy-Pf7"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="cnK-Pa-DDF" secondAttribute="trailing" constant="20" id="9P7-Or-S8M"/>
<constraint firstAttribute="bottom" secondItem="fPZ-Vc-pTX" secondAttribute="bottom" constant="11.5" id="BD3-7Z-Ry9"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="centerY" secondItem="fPZ-Vc-pTX" secondAttribute="centerY" id="Q4G-6M-3Qe"/>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="top" secondItem="1TD-My-nqW" secondAttribute="top" constant="11.5" id="lOh-MF-Khj"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="trailing" constant="12" id="mVz-me-wRN"/>
</constraints>
</view>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="1TD-My-nqW" secondAttribute="bottom" id="fgL-GE-OC3"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="leading" secondItem="FO6-8m-8lR" secondAttribute="leading" id="iV5-qZ-Oq7"/>
<constraint firstAttribute="trailing" secondItem="1TD-My-nqW" secondAttribute="trailing" id="whk-Ke-oc7"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="top" secondItem="FO6-8m-8lR" secondAttribute="top" id="yIU-Lz-jlC"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="leftLabel" destination="Gsx-qe-uXG" id="9kR-67-2oC"/>
<outlet property="rightLabel" destination="cnK-Pa-DDF" id="p4k-MJ-gb2"/>
</connections>
<point key="canvasLocation" x="156" y="50.374812593703155"/>
</tableViewCell>
</objects>
</document>
and example cell and table view controller classes:
class ScrollingLabelCell: UITableViewCell
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
class ScrollingLabelTableViewController: UITableViewController
let xibName = "ScrollingLabelCell"
let theData: [[String]] = [
["Example Name", "1"],
["Example Longer Name", "2"],
["Example Even Longer Name", "3"],
["To demonstrate the scrolling,", "4"],
["6, 7 & 800 have the same name", "5"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "6"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "7"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "800"],
["Back to Short Names", "99"],
["With longer numbers", "2,750"],
]
override func viewDidLoad()
super.viewDidLoad()
let bundle = Bundle(for: type(of: self))
let cellNib = UINib(nibName: xibName, bundle: bundle)
tableView.register(cellNib, forCellReuseIdentifier: xibName)
override func numberOfSections(in tableView: UITableView) -> Int
return 1
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return theData.count
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: xibName, for: indexPath) as! ScrollingLabelCell
cell.leftLabel.text = theData[indexPath.row][0]
cell.rightLabel.text = "(" + theData[indexPath.row][1] + ")"
return cell
I almost work. Please look at my edited question.
– matekome
Mar 9 at 14:26
Did you try using the code and Storyboard that I posted? Because that worked for me, including scrolling the left label (see the screen cap). If you're getting truncated instead of scrolling, I suspect you're missing a constraint / setting.
– DonMag
Mar 9 at 14:55
@matekome - see my edited answer
– DonMag
Mar 11 at 13:09
add a comment |
A little tricky, but not too tricky...
What you need to do is set multiple, similar constraints and use a combination of Content Compression Resistance Priority
and Constraint Priority
on the different elements.
Take a look at this:
- We embed Left Label in a scroll view.
- We constrain the width of the scroll view to the width of the label, but with a Priority of
750
. That will allow the scroll view to expand (and contract) with the label until it can't expand anymore. - We add constraints to Right Label... leading to the scroll view, and trailing to the right edge of the view, with the trailing set to
>= 20
and the compression resistance set to1000
. That allows the label to "stick" to the scroll view as it expands / contracts, but will not allow it to go past the right edge, nor compress past its own content width. - The rest of the constraints are pretty standard.
And we get:
I whipped up a simple example that will let you change the text with button taps to see it in action:
Here's the class:
class ScrollingLabelViewController: UIViewController
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
override func viewDidLoad()
super.viewDidLoad()
@IBAction func leftTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
leftLabel.text = "Example Name"
case "Medium Text":
leftLabel.text = "Example Longer Name"
case "Long Text":
fallthrough
default:
leftLabel.text = "Example Name that is long enough that it will need to scroll."
@IBAction func rightTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
rightLabel.text = "(6)"
case "Medium Text":
rightLabel.text = "(255)"
case "Long Text":
fallthrough
default:
rightLabel.text = "(38,872)"
And the Storyboard source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="itP-Si-dAD">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Scrolling Label View Controller-->
<scene sceneID="2HK-o9-I65">
<objects>
<viewController id="itP-Si-dAD" customClass="ScrollingLabelViewController" customModule="XC10SWScratch" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="C9r-ad-Wv2">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Rs3-TC-hFe">
<rect key="frame" x="20" y="60" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="3jj-Oq-9XF">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="3jj-Oq-9XF" secondAttribute="bottom" id="7EF-mm-DaK"/>
<constraint firstAttribute="width" secondItem="3jj-Oq-9XF" secondAttribute="width" priority="750" id="ZtX-rP-Lme"/>
<constraint firstAttribute="width" relation="greaterThanOrEqual" constant="12" id="ZyU-il-ReF"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="top" id="ml2-6X-bBl"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="leading" id="r4q-LE-OQ5"/>
<constraint firstAttribute="trailing" secondItem="3jj-Oq-9XF" secondAttribute="trailing" id="t9q-89-BOF"/>
<constraint firstAttribute="height" secondItem="3jj-Oq-9XF" secondAttribute="height" id="xDp-np-bFT"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ZCj-c5-IzQ">
<rect key="frame" x="142.5" y="60" width="23" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<stackView opaque="NO" contentMode="scaleToFill" spacing="47" translatesAutoresizingMaskIntoConstraints="NO" id="0v3-eY-MTM">
<rect key="frame" x="44" y="160.5" width="287" height="164.5"/>
<subviews>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="nou-P9-haw">
<rect key="frame" x="0.0" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Left Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Jgc-gS-1Oz">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mPG-zF-zdi">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="z5m-yd-ACM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="xiv-Uc-UPL">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="hCp-75-WVo"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="LQD-gc-Pv1">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="fWI-cl-wGZ"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="Mvo-co-QSU"/>
</constraints>
</stackView>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="usT-YQ-P4a">
<rect key="frame" x="167" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Right Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="WXA-Lo-BaW">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="UXZ-r3-dw1">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="1e8-Dh-iHD"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="BN2-Tt-2QG">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="8CM-Gx-TYM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="vCy-ut-LXL">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="iTb-4n-jbd"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="ACw-Tb-RfF"/>
</constraints>
</stackView>
</subviews>
</stackView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="leading" secondItem="N2s-Cz-Yp4" secondAttribute="leading" constant="20" id="Dkw-df-pKY"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="centerY" secondItem="Rs3-TC-hFe" secondAttribute="centerY" id="GsG-U4-jc6"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="trailing" constant="8" id="aVZ-i7-91I"/>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="top" secondItem="N2s-Cz-Yp4" secondAttribute="top" constant="40" id="jFX-1U-cRh"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="centerX" secondItem="C9r-ad-Wv2" secondAttribute="centerX" id="jZO-qZ-0z5"/>
<constraint firstItem="N2s-Cz-Yp4" firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="ZCj-c5-IzQ" secondAttribute="trailing" constant="20" id="pP1-gC-Uvq"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="bottom" constant="80" id="sJi-4A-BOA"/>
</constraints>
<viewLayoutGuide key="safeArea" id="N2s-Cz-Yp4"/>
</view>
<connections>
<outlet property="leftLabel" destination="3jj-Oq-9XF" id="469-ke-ni2"/>
<outlet property="rightLabel" destination="ZCj-c5-IzQ" id="hMG-sN-B29"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="w9F-EF-F89" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="167" y="1506"/>
</scene>
</scenes>
</document>
Edit: pretty much the same thing, but setup as a XIB for use as a table view cell.
ScrollingLabelCell.xib
in IB:
ScrollingLabelCell.xib
source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" id="SVi-M2-eJO" customClass="ScrollingLabelCell" customModule="XC10SWScratch" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="SVi-M2-eJO" id="FO6-8m-8lR">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="1TD-My-nqW" userLabel="Inner View">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="fPZ-Vc-pTX">
<rect key="frame" x="16" y="11.5" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Gsx-qe-uXG">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="Gsx-qe-uXG" secondAttribute="bottom" id="KNJ-P5-R1c"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="top" secondItem="fPZ-Vc-pTX" secondAttribute="top" id="M63-Na-FHd"/>
<constraint firstAttribute="height" secondItem="Gsx-qe-uXG" secondAttribute="height" id="kQb-o9-Cmr"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="leading" id="od5-IF-Drl"/>
<constraint firstAttribute="trailing" secondItem="Gsx-qe-uXG" secondAttribute="trailing" id="pVh-95-8bc"/>
<constraint firstAttribute="width" secondItem="Gsx-qe-uXG" secondAttribute="width" priority="750" id="zUu-pN-rme"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="cnK-Pa-DDF">
<rect key="frame" x="142.5" y="11.5" width="23" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="leading" secondItem="1TD-My-nqW" secondAttribute="leading" constant="16" id="24S-Dy-Pf7"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="cnK-Pa-DDF" secondAttribute="trailing" constant="20" id="9P7-Or-S8M"/>
<constraint firstAttribute="bottom" secondItem="fPZ-Vc-pTX" secondAttribute="bottom" constant="11.5" id="BD3-7Z-Ry9"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="centerY" secondItem="fPZ-Vc-pTX" secondAttribute="centerY" id="Q4G-6M-3Qe"/>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="top" secondItem="1TD-My-nqW" secondAttribute="top" constant="11.5" id="lOh-MF-Khj"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="trailing" constant="12" id="mVz-me-wRN"/>
</constraints>
</view>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="1TD-My-nqW" secondAttribute="bottom" id="fgL-GE-OC3"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="leading" secondItem="FO6-8m-8lR" secondAttribute="leading" id="iV5-qZ-Oq7"/>
<constraint firstAttribute="trailing" secondItem="1TD-My-nqW" secondAttribute="trailing" id="whk-Ke-oc7"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="top" secondItem="FO6-8m-8lR" secondAttribute="top" id="yIU-Lz-jlC"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="leftLabel" destination="Gsx-qe-uXG" id="9kR-67-2oC"/>
<outlet property="rightLabel" destination="cnK-Pa-DDF" id="p4k-MJ-gb2"/>
</connections>
<point key="canvasLocation" x="156" y="50.374812593703155"/>
</tableViewCell>
</objects>
</document>
and example cell and table view controller classes:
class ScrollingLabelCell: UITableViewCell
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
class ScrollingLabelTableViewController: UITableViewController
let xibName = "ScrollingLabelCell"
let theData: [[String]] = [
["Example Name", "1"],
["Example Longer Name", "2"],
["Example Even Longer Name", "3"],
["To demonstrate the scrolling,", "4"],
["6, 7 & 800 have the same name", "5"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "6"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "7"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "800"],
["Back to Short Names", "99"],
["With longer numbers", "2,750"],
]
override func viewDidLoad()
super.viewDidLoad()
let bundle = Bundle(for: type(of: self))
let cellNib = UINib(nibName: xibName, bundle: bundle)
tableView.register(cellNib, forCellReuseIdentifier: xibName)
override func numberOfSections(in tableView: UITableView) -> Int
return 1
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return theData.count
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: xibName, for: indexPath) as! ScrollingLabelCell
cell.leftLabel.text = theData[indexPath.row][0]
cell.rightLabel.text = "(" + theData[indexPath.row][1] + ")"
return cell
I almost work. Please look at my edited question.
– matekome
Mar 9 at 14:26
Did you try using the code and Storyboard that I posted? Because that worked for me, including scrolling the left label (see the screen cap). If you're getting truncated instead of scrolling, I suspect you're missing a constraint / setting.
– DonMag
Mar 9 at 14:55
@matekome - see my edited answer
– DonMag
Mar 11 at 13:09
add a comment |
A little tricky, but not too tricky...
What you need to do is set multiple, similar constraints and use a combination of Content Compression Resistance Priority
and Constraint Priority
on the different elements.
Take a look at this:
- We embed Left Label in a scroll view.
- We constrain the width of the scroll view to the width of the label, but with a Priority of
750
. That will allow the scroll view to expand (and contract) with the label until it can't expand anymore. - We add constraints to Right Label... leading to the scroll view, and trailing to the right edge of the view, with the trailing set to
>= 20
and the compression resistance set to1000
. That allows the label to "stick" to the scroll view as it expands / contracts, but will not allow it to go past the right edge, nor compress past its own content width. - The rest of the constraints are pretty standard.
And we get:
I whipped up a simple example that will let you change the text with button taps to see it in action:
Here's the class:
class ScrollingLabelViewController: UIViewController
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
override func viewDidLoad()
super.viewDidLoad()
@IBAction func leftTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
leftLabel.text = "Example Name"
case "Medium Text":
leftLabel.text = "Example Longer Name"
case "Long Text":
fallthrough
default:
leftLabel.text = "Example Name that is long enough that it will need to scroll."
@IBAction func rightTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
rightLabel.text = "(6)"
case "Medium Text":
rightLabel.text = "(255)"
case "Long Text":
fallthrough
default:
rightLabel.text = "(38,872)"
And the Storyboard source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="itP-Si-dAD">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Scrolling Label View Controller-->
<scene sceneID="2HK-o9-I65">
<objects>
<viewController id="itP-Si-dAD" customClass="ScrollingLabelViewController" customModule="XC10SWScratch" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="C9r-ad-Wv2">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Rs3-TC-hFe">
<rect key="frame" x="20" y="60" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="3jj-Oq-9XF">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="3jj-Oq-9XF" secondAttribute="bottom" id="7EF-mm-DaK"/>
<constraint firstAttribute="width" secondItem="3jj-Oq-9XF" secondAttribute="width" priority="750" id="ZtX-rP-Lme"/>
<constraint firstAttribute="width" relation="greaterThanOrEqual" constant="12" id="ZyU-il-ReF"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="top" id="ml2-6X-bBl"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="leading" id="r4q-LE-OQ5"/>
<constraint firstAttribute="trailing" secondItem="3jj-Oq-9XF" secondAttribute="trailing" id="t9q-89-BOF"/>
<constraint firstAttribute="height" secondItem="3jj-Oq-9XF" secondAttribute="height" id="xDp-np-bFT"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ZCj-c5-IzQ">
<rect key="frame" x="142.5" y="60" width="23" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<stackView opaque="NO" contentMode="scaleToFill" spacing="47" translatesAutoresizingMaskIntoConstraints="NO" id="0v3-eY-MTM">
<rect key="frame" x="44" y="160.5" width="287" height="164.5"/>
<subviews>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="nou-P9-haw">
<rect key="frame" x="0.0" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Left Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Jgc-gS-1Oz">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mPG-zF-zdi">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="z5m-yd-ACM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="xiv-Uc-UPL">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="hCp-75-WVo"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="LQD-gc-Pv1">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="fWI-cl-wGZ"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="Mvo-co-QSU"/>
</constraints>
</stackView>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="usT-YQ-P4a">
<rect key="frame" x="167" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Right Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="WXA-Lo-BaW">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="UXZ-r3-dw1">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="1e8-Dh-iHD"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="BN2-Tt-2QG">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="8CM-Gx-TYM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="vCy-ut-LXL">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="iTb-4n-jbd"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="ACw-Tb-RfF"/>
</constraints>
</stackView>
</subviews>
</stackView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="leading" secondItem="N2s-Cz-Yp4" secondAttribute="leading" constant="20" id="Dkw-df-pKY"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="centerY" secondItem="Rs3-TC-hFe" secondAttribute="centerY" id="GsG-U4-jc6"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="trailing" constant="8" id="aVZ-i7-91I"/>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="top" secondItem="N2s-Cz-Yp4" secondAttribute="top" constant="40" id="jFX-1U-cRh"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="centerX" secondItem="C9r-ad-Wv2" secondAttribute="centerX" id="jZO-qZ-0z5"/>
<constraint firstItem="N2s-Cz-Yp4" firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="ZCj-c5-IzQ" secondAttribute="trailing" constant="20" id="pP1-gC-Uvq"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="bottom" constant="80" id="sJi-4A-BOA"/>
</constraints>
<viewLayoutGuide key="safeArea" id="N2s-Cz-Yp4"/>
</view>
<connections>
<outlet property="leftLabel" destination="3jj-Oq-9XF" id="469-ke-ni2"/>
<outlet property="rightLabel" destination="ZCj-c5-IzQ" id="hMG-sN-B29"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="w9F-EF-F89" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="167" y="1506"/>
</scene>
</scenes>
</document>
Edit: pretty much the same thing, but setup as a XIB for use as a table view cell.
ScrollingLabelCell.xib
in IB:
ScrollingLabelCell.xib
source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" id="SVi-M2-eJO" customClass="ScrollingLabelCell" customModule="XC10SWScratch" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="SVi-M2-eJO" id="FO6-8m-8lR">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="1TD-My-nqW" userLabel="Inner View">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="fPZ-Vc-pTX">
<rect key="frame" x="16" y="11.5" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Gsx-qe-uXG">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="Gsx-qe-uXG" secondAttribute="bottom" id="KNJ-P5-R1c"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="top" secondItem="fPZ-Vc-pTX" secondAttribute="top" id="M63-Na-FHd"/>
<constraint firstAttribute="height" secondItem="Gsx-qe-uXG" secondAttribute="height" id="kQb-o9-Cmr"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="leading" id="od5-IF-Drl"/>
<constraint firstAttribute="trailing" secondItem="Gsx-qe-uXG" secondAttribute="trailing" id="pVh-95-8bc"/>
<constraint firstAttribute="width" secondItem="Gsx-qe-uXG" secondAttribute="width" priority="750" id="zUu-pN-rme"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="cnK-Pa-DDF">
<rect key="frame" x="142.5" y="11.5" width="23" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="leading" secondItem="1TD-My-nqW" secondAttribute="leading" constant="16" id="24S-Dy-Pf7"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="cnK-Pa-DDF" secondAttribute="trailing" constant="20" id="9P7-Or-S8M"/>
<constraint firstAttribute="bottom" secondItem="fPZ-Vc-pTX" secondAttribute="bottom" constant="11.5" id="BD3-7Z-Ry9"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="centerY" secondItem="fPZ-Vc-pTX" secondAttribute="centerY" id="Q4G-6M-3Qe"/>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="top" secondItem="1TD-My-nqW" secondAttribute="top" constant="11.5" id="lOh-MF-Khj"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="trailing" constant="12" id="mVz-me-wRN"/>
</constraints>
</view>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="1TD-My-nqW" secondAttribute="bottom" id="fgL-GE-OC3"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="leading" secondItem="FO6-8m-8lR" secondAttribute="leading" id="iV5-qZ-Oq7"/>
<constraint firstAttribute="trailing" secondItem="1TD-My-nqW" secondAttribute="trailing" id="whk-Ke-oc7"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="top" secondItem="FO6-8m-8lR" secondAttribute="top" id="yIU-Lz-jlC"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="leftLabel" destination="Gsx-qe-uXG" id="9kR-67-2oC"/>
<outlet property="rightLabel" destination="cnK-Pa-DDF" id="p4k-MJ-gb2"/>
</connections>
<point key="canvasLocation" x="156" y="50.374812593703155"/>
</tableViewCell>
</objects>
</document>
and example cell and table view controller classes:
class ScrollingLabelCell: UITableViewCell
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
class ScrollingLabelTableViewController: UITableViewController
let xibName = "ScrollingLabelCell"
let theData: [[String]] = [
["Example Name", "1"],
["Example Longer Name", "2"],
["Example Even Longer Name", "3"],
["To demonstrate the scrolling,", "4"],
["6, 7 & 800 have the same name", "5"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "6"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "7"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "800"],
["Back to Short Names", "99"],
["With longer numbers", "2,750"],
]
override func viewDidLoad()
super.viewDidLoad()
let bundle = Bundle(for: type(of: self))
let cellNib = UINib(nibName: xibName, bundle: bundle)
tableView.register(cellNib, forCellReuseIdentifier: xibName)
override func numberOfSections(in tableView: UITableView) -> Int
return 1
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return theData.count
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: xibName, for: indexPath) as! ScrollingLabelCell
cell.leftLabel.text = theData[indexPath.row][0]
cell.rightLabel.text = "(" + theData[indexPath.row][1] + ")"
return cell
A little tricky, but not too tricky...
What you need to do is set multiple, similar constraints and use a combination of Content Compression Resistance Priority
and Constraint Priority
on the different elements.
Take a look at this:
- We embed Left Label in a scroll view.
- We constrain the width of the scroll view to the width of the label, but with a Priority of
750
. That will allow the scroll view to expand (and contract) with the label until it can't expand anymore. - We add constraints to Right Label... leading to the scroll view, and trailing to the right edge of the view, with the trailing set to
>= 20
and the compression resistance set to1000
. That allows the label to "stick" to the scroll view as it expands / contracts, but will not allow it to go past the right edge, nor compress past its own content width. - The rest of the constraints are pretty standard.
And we get:
I whipped up a simple example that will let you change the text with button taps to see it in action:
Here's the class:
class ScrollingLabelViewController: UIViewController
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
override func viewDidLoad()
super.viewDidLoad()
@IBAction func leftTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
leftLabel.text = "Example Name"
case "Medium Text":
leftLabel.text = "Example Longer Name"
case "Long Text":
fallthrough
default:
leftLabel.text = "Example Name that is long enough that it will need to scroll."
@IBAction func rightTap(_ sender: Any)
if let btn = sender as? UIButton
let t = btn.currentTitle
switch t
case "Short Text":
rightLabel.text = "(6)"
case "Medium Text":
rightLabel.text = "(255)"
case "Long Text":
fallthrough
default:
rightLabel.text = "(38,872)"
And the Storyboard source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="itP-Si-dAD">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Scrolling Label View Controller-->
<scene sceneID="2HK-o9-I65">
<objects>
<viewController id="itP-Si-dAD" customClass="ScrollingLabelViewController" customModule="XC10SWScratch" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="C9r-ad-Wv2">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Rs3-TC-hFe">
<rect key="frame" x="20" y="60" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="3jj-Oq-9XF">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="3jj-Oq-9XF" secondAttribute="bottom" id="7EF-mm-DaK"/>
<constraint firstAttribute="width" secondItem="3jj-Oq-9XF" secondAttribute="width" priority="750" id="ZtX-rP-Lme"/>
<constraint firstAttribute="width" relation="greaterThanOrEqual" constant="12" id="ZyU-il-ReF"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="top" id="ml2-6X-bBl"/>
<constraint firstItem="3jj-Oq-9XF" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="leading" id="r4q-LE-OQ5"/>
<constraint firstAttribute="trailing" secondItem="3jj-Oq-9XF" secondAttribute="trailing" id="t9q-89-BOF"/>
<constraint firstAttribute="height" secondItem="3jj-Oq-9XF" secondAttribute="height" id="xDp-np-bFT"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ZCj-c5-IzQ">
<rect key="frame" x="142.5" y="60" width="23" height="20.5"/>
<color key="backgroundColor" red="0.0" green="0.99143940210000003" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<stackView opaque="NO" contentMode="scaleToFill" spacing="47" translatesAutoresizingMaskIntoConstraints="NO" id="0v3-eY-MTM">
<rect key="frame" x="44" y="160.5" width="287" height="164.5"/>
<subviews>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="nou-P9-haw">
<rect key="frame" x="0.0" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Left Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Jgc-gS-1Oz">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mPG-zF-zdi">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="z5m-yd-ACM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="xiv-Uc-UPL">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="hCp-75-WVo"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="LQD-gc-Pv1">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="leftTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="fWI-cl-wGZ"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="Mvo-co-QSU"/>
</constraints>
</stackView>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="18" translatesAutoresizingMaskIntoConstraints="NO" id="usT-YQ-P4a">
<rect key="frame" x="167" y="0.0" width="120" height="164.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Right Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="WXA-Lo-BaW">
<rect key="frame" x="0.0" y="0.0" width="120" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="UXZ-r3-dw1">
<rect key="frame" x="0.0" y="38.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Short Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="1e8-Dh-iHD"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="BN2-Tt-2QG">
<rect key="frame" x="0.0" y="86.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Medium Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="8CM-Gx-TYM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="vCy-ut-LXL">
<rect key="frame" x="0.0" y="134.5" width="120" height="30"/>
<color key="backgroundColor" red="0.92143100499999997" green="0.92145264149999995" blue="0.92144101860000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<state key="normal" title="Long Text"/>
<connections>
<action selector="rightTap:" destination="itP-Si-dAD" eventType="touchUpInside" id="iTb-4n-jbd"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="width" constant="120" id="ACw-Tb-RfF"/>
</constraints>
</stackView>
</subviews>
</stackView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="leading" secondItem="N2s-Cz-Yp4" secondAttribute="leading" constant="20" id="Dkw-df-pKY"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="centerY" secondItem="Rs3-TC-hFe" secondAttribute="centerY" id="GsG-U4-jc6"/>
<constraint firstItem="ZCj-c5-IzQ" firstAttribute="leading" secondItem="Rs3-TC-hFe" secondAttribute="trailing" constant="8" id="aVZ-i7-91I"/>
<constraint firstItem="Rs3-TC-hFe" firstAttribute="top" secondItem="N2s-Cz-Yp4" secondAttribute="top" constant="40" id="jFX-1U-cRh"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="centerX" secondItem="C9r-ad-Wv2" secondAttribute="centerX" id="jZO-qZ-0z5"/>
<constraint firstItem="N2s-Cz-Yp4" firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="ZCj-c5-IzQ" secondAttribute="trailing" constant="20" id="pP1-gC-Uvq"/>
<constraint firstItem="0v3-eY-MTM" firstAttribute="top" secondItem="Rs3-TC-hFe" secondAttribute="bottom" constant="80" id="sJi-4A-BOA"/>
</constraints>
<viewLayoutGuide key="safeArea" id="N2s-Cz-Yp4"/>
</view>
<connections>
<outlet property="leftLabel" destination="3jj-Oq-9XF" id="469-ke-ni2"/>
<outlet property="rightLabel" destination="ZCj-c5-IzQ" id="hMG-sN-B29"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="w9F-EF-F89" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="167" y="1506"/>
</scene>
</scenes>
</document>
Edit: pretty much the same thing, but setup as a XIB for use as a table view cell.
ScrollingLabelCell.xib
in IB:
ScrollingLabelCell.xib
source:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" id="SVi-M2-eJO" customClass="ScrollingLabelCell" customModule="XC10SWScratch" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="SVi-M2-eJO" id="FO6-8m-8lR">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="1TD-My-nqW" userLabel="Inner View">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="fPZ-Vc-pTX">
<rect key="frame" x="16" y="11.5" width="114.5" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Example Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Gsx-qe-uXG">
<rect key="frame" x="0.0" y="0.0" width="114.5" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="Gsx-qe-uXG" secondAttribute="bottom" id="KNJ-P5-R1c"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="top" secondItem="fPZ-Vc-pTX" secondAttribute="top" id="M63-Na-FHd"/>
<constraint firstAttribute="height" secondItem="Gsx-qe-uXG" secondAttribute="height" id="kQb-o9-Cmr"/>
<constraint firstItem="Gsx-qe-uXG" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="leading" id="od5-IF-Drl"/>
<constraint firstAttribute="trailing" secondItem="Gsx-qe-uXG" secondAttribute="trailing" id="pVh-95-8bc"/>
<constraint firstAttribute="width" secondItem="Gsx-qe-uXG" secondAttribute="width" priority="750" id="zUu-pN-rme"/>
</constraints>
</scrollView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="(6)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="cnK-Pa-DDF">
<rect key="frame" x="142.5" y="11.5" width="23" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="leading" secondItem="1TD-My-nqW" secondAttribute="leading" constant="16" id="24S-Dy-Pf7"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="cnK-Pa-DDF" secondAttribute="trailing" constant="20" id="9P7-Or-S8M"/>
<constraint firstAttribute="bottom" secondItem="fPZ-Vc-pTX" secondAttribute="bottom" constant="11.5" id="BD3-7Z-Ry9"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="centerY" secondItem="fPZ-Vc-pTX" secondAttribute="centerY" id="Q4G-6M-3Qe"/>
<constraint firstItem="fPZ-Vc-pTX" firstAttribute="top" secondItem="1TD-My-nqW" secondAttribute="top" constant="11.5" id="lOh-MF-Khj"/>
<constraint firstItem="cnK-Pa-DDF" firstAttribute="leading" secondItem="fPZ-Vc-pTX" secondAttribute="trailing" constant="12" id="mVz-me-wRN"/>
</constraints>
</view>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="1TD-My-nqW" secondAttribute="bottom" id="fgL-GE-OC3"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="leading" secondItem="FO6-8m-8lR" secondAttribute="leading" id="iV5-qZ-Oq7"/>
<constraint firstAttribute="trailing" secondItem="1TD-My-nqW" secondAttribute="trailing" id="whk-Ke-oc7"/>
<constraint firstItem="1TD-My-nqW" firstAttribute="top" secondItem="FO6-8m-8lR" secondAttribute="top" id="yIU-Lz-jlC"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="leftLabel" destination="Gsx-qe-uXG" id="9kR-67-2oC"/>
<outlet property="rightLabel" destination="cnK-Pa-DDF" id="p4k-MJ-gb2"/>
</connections>
<point key="canvasLocation" x="156" y="50.374812593703155"/>
</tableViewCell>
</objects>
</document>
and example cell and table view controller classes:
class ScrollingLabelCell: UITableViewCell
@IBOutlet var leftLabel: UILabel!
@IBOutlet var rightLabel: UILabel!
class ScrollingLabelTableViewController: UITableViewController
let xibName = "ScrollingLabelCell"
let theData: [[String]] = [
["Example Name", "1"],
["Example Longer Name", "2"],
["Example Even Longer Name", "3"],
["To demonstrate the scrolling,", "4"],
["6, 7 & 800 have the same name", "5"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "6"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "7"],
["Mr. Example Name that is Long Enough that it Needs to Scroll", "800"],
["Back to Short Names", "99"],
["With longer numbers", "2,750"],
]
override func viewDidLoad()
super.viewDidLoad()
let bundle = Bundle(for: type(of: self))
let cellNib = UINib(nibName: xibName, bundle: bundle)
tableView.register(cellNib, forCellReuseIdentifier: xibName)
override func numberOfSections(in tableView: UITableView) -> Int
return 1
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return theData.count
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: xibName, for: indexPath) as! ScrollingLabelCell
cell.leftLabel.text = theData[indexPath.row][0]
cell.rightLabel.text = "(" + theData[indexPath.row][1] + ")"
return cell
edited Mar 11 at 13:08
answered Mar 8 at 14:09
DonMagDonMag
18.1k21130
18.1k21130
I almost work. Please look at my edited question.
– matekome
Mar 9 at 14:26
Did you try using the code and Storyboard that I posted? Because that worked for me, including scrolling the left label (see the screen cap). If you're getting truncated instead of scrolling, I suspect you're missing a constraint / setting.
– DonMag
Mar 9 at 14:55
@matekome - see my edited answer
– DonMag
Mar 11 at 13:09
add a comment |
I almost work. Please look at my edited question.
– matekome
Mar 9 at 14:26
Did you try using the code and Storyboard that I posted? Because that worked for me, including scrolling the left label (see the screen cap). If you're getting truncated instead of scrolling, I suspect you're missing a constraint / setting.
– DonMag
Mar 9 at 14:55
@matekome - see my edited answer
– DonMag
Mar 11 at 13:09
I almost work. Please look at my edited question.
– matekome
Mar 9 at 14:26
I almost work. Please look at my edited question.
– matekome
Mar 9 at 14:26
Did you try using the code and Storyboard that I posted? Because that worked for me, including scrolling the left label (see the screen cap). If you're getting truncated instead of scrolling, I suspect you're missing a constraint / setting.
– DonMag
Mar 9 at 14:55
Did you try using the code and Storyboard that I posted? Because that worked for me, including scrolling the left label (see the screen cap). If you're getting truncated instead of scrolling, I suspect you're missing a constraint / setting.
– DonMag
Mar 9 at 14:55
@matekome - see my edited answer
– DonMag
Mar 11 at 13:09
@matekome - see my edited answer
– DonMag
Mar 11 at 13:09
add a comment |
You can accomplish this either with constraints, or you can try playing around with stackViews, since this is generally their intended use:
UIStackview
| Label 1 | UIScrollView (Label 2) |
In this case, just add the width constraint to the scrollView
to be >= than your intended size and increase the vertical priority for the label 1
.
I would also reconsider against having the label inside a scrollView, inside another scrollView (your tableView in this specific case) since it will be pretty janky to get something that small to scroll. Probably better to just consider placing the labels one underneath the other or some other layout improvement requiring less tweaking and having a better UX.
I'm not sure you understood me well. First label should be scrollable if is too long. So i will scroll something which is not too small to scroll. I only whant want twol labels next to each other in one row but second label should be always visible. I don't want second label be out of the screen so if first label is too long it should be scrollable but second one should be still on the screen.
– matekome
Mar 8 at 12:15
The principle is still the same, wherever the scrollView is.
– Adis
Mar 8 at 15:02
add a comment |
You can accomplish this either with constraints, or you can try playing around with stackViews, since this is generally their intended use:
UIStackview
| Label 1 | UIScrollView (Label 2) |
In this case, just add the width constraint to the scrollView
to be >= than your intended size and increase the vertical priority for the label 1
.
I would also reconsider against having the label inside a scrollView, inside another scrollView (your tableView in this specific case) since it will be pretty janky to get something that small to scroll. Probably better to just consider placing the labels one underneath the other or some other layout improvement requiring less tweaking and having a better UX.
I'm not sure you understood me well. First label should be scrollable if is too long. So i will scroll something which is not too small to scroll. I only whant want twol labels next to each other in one row but second label should be always visible. I don't want second label be out of the screen so if first label is too long it should be scrollable but second one should be still on the screen.
– matekome
Mar 8 at 12:15
The principle is still the same, wherever the scrollView is.
– Adis
Mar 8 at 15:02
add a comment |
You can accomplish this either with constraints, or you can try playing around with stackViews, since this is generally their intended use:
UIStackview
| Label 1 | UIScrollView (Label 2) |
In this case, just add the width constraint to the scrollView
to be >= than your intended size and increase the vertical priority for the label 1
.
I would also reconsider against having the label inside a scrollView, inside another scrollView (your tableView in this specific case) since it will be pretty janky to get something that small to scroll. Probably better to just consider placing the labels one underneath the other or some other layout improvement requiring less tweaking and having a better UX.
You can accomplish this either with constraints, or you can try playing around with stackViews, since this is generally their intended use:
UIStackview
| Label 1 | UIScrollView (Label 2) |
In this case, just add the width constraint to the scrollView
to be >= than your intended size and increase the vertical priority for the label 1
.
I would also reconsider against having the label inside a scrollView, inside another scrollView (your tableView in this specific case) since it will be pretty janky to get something that small to scroll. Probably better to just consider placing the labels one underneath the other or some other layout improvement requiring less tweaking and having a better UX.
answered Mar 8 at 12:00
AdisAdis
2,64022130
2,64022130
I'm not sure you understood me well. First label should be scrollable if is too long. So i will scroll something which is not too small to scroll. I only whant want twol labels next to each other in one row but second label should be always visible. I don't want second label be out of the screen so if first label is too long it should be scrollable but second one should be still on the screen.
– matekome
Mar 8 at 12:15
The principle is still the same, wherever the scrollView is.
– Adis
Mar 8 at 15:02
add a comment |
I'm not sure you understood me well. First label should be scrollable if is too long. So i will scroll something which is not too small to scroll. I only whant want twol labels next to each other in one row but second label should be always visible. I don't want second label be out of the screen so if first label is too long it should be scrollable but second one should be still on the screen.
– matekome
Mar 8 at 12:15
The principle is still the same, wherever the scrollView is.
– Adis
Mar 8 at 15:02
I'm not sure you understood me well. First label should be scrollable if is too long. So i will scroll something which is not too small to scroll. I only whant want twol labels next to each other in one row but second label should be always visible. I don't want second label be out of the screen so if first label is too long it should be scrollable but second one should be still on the screen.
– matekome
Mar 8 at 12:15
I'm not sure you understood me well. First label should be scrollable if is too long. So i will scroll something which is not too small to scroll. I only whant want twol labels next to each other in one row but second label should be always visible. I don't want second label be out of the screen so if first label is too long it should be scrollable but second one should be still on the screen.
– matekome
Mar 8 at 12:15
The principle is still the same, wherever the scrollView is.
– Adis
Mar 8 at 15:02
The principle is still the same, wherever the scrollView is.
– Adis
Mar 8 at 15:02
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55061924%2flabel-next-to-a-label-with-variable-length%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Have you tried setting content hugging priority for both the labels ? High value of hugging priority will take the priority and expand the intrinsic size.
– Bharath Vankireddy
Mar 8 at 11:26
I have added Label1's settings to my question. This settings doesn't work.
– matekome
Mar 8 at 12:05
@matekome - not quite clear what you're trying to do. If your labels are (
L1
) "abc" and (L2
) "123456789", you want it displayed withL1
followed by a small space thenL2
followed by a large space to the edge of the view? And asL1
has more text, it pushesL2
to the right, untilL2
hits the edge and thenL1
scrolls? Or do you want it to start as in your image, withL2
always at the right edge?– DonMag
Mar 8 at 13:22
I have extended my example. Please look at my edited question.
– matekome
Mar 8 at 13:45