1

I'm making a simple calculator in iOS, and I want the user to be able to scroll the label horizontally when the end gets truncated.

How would I go about doing this? My original idea was to make two buttons that would move the label left or right by using stringpadtoLength type of method, but that seemed inefficient.

user2329239
  • 59
  • 2
  • 8

2 Answers2

1

I see two ways of building this.

  1. Use a UITextView and always return NO from -textFieldShouldBeginEditing:. This should get you 90% the way there very fast.

  2. Build a custom control using a UIScrollView which contains a UILabel that uses -sizeToFit. This will be a bit more work, but will do exactly what you expect.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • I have made the textview, but how can I limit it to just horizontal scrolling? I don't want the calculations to be continued onto the next line of the text view, I want it to continue horizontally with the option to scroll left and right. – user2329239 Jun 04 '13 at 04:27
  • @user2329239 Make sure the text view is set for horizontal scrolling, then adjust the width on `-textViewDidChange:` (see http://stackoverflow.com/questions/6263161/uitextview-just-horizontal-scrolling-help) – Jeffery Thomas Jun 04 '13 at 10:42
1

I went for Jefferey's second suggestion because I thought it would give a "cleaner" result. Turns out, it's not that easy to implement. Here's what you have to be careful about when you're putting a single-line UILabel inside of UIScrollView, in order to be able to scroll horizontally through the text.

  • The parent UIViewController should have the box "Adjust scroll view insets" unchecked. If you forget this your text may be placed below the content of the UIScrollView, meaning that you can only see it if you hold it while over-scrolling down.
  • Call [self.toolboxItemNameLabel sizeToFit]; in your UIViewController's viewDidLoad in order to set the right size for your UILabel. This ensures that the scrolling is comfortable, going from the left to the right of the text.
  • When using autolayout, you must add constraints for the leading and trailing space to container of the UILabel which is inside of the UIScrollView. Thanks to this great post for the answer.
Community
  • 1
  • 1
Martin Devillers
  • 720
  • 8
  • 11
  • Hi Martin, Thanks for the tips. After reading your other post, I still have an issue where my label now scrolls but does not scroll to the end of the text content. Am I missing anything obvious? – Tommie C. Nov 14 '14 at 21:38