ios - Auto-Stretching UITextField on typing -
i have uitextfield
created programatically. want have uneditable prefixed characters on beginning , end, such
"hello [textfield] world".
first, tried adding characters manually , using shouldchangecharactersinrange
make approach won't work because if user long press on textfield , come beginning, can edit first characters (so can mess prefixed characters). option didn't seem convenient.
another option creating empty uitextfield
, , 2 static uilabels
(for "hello" , "world"). here, problem arises. uitextfield
's text center aligned (and vertically centered in view), giving width of view , 0 x-axis (so textfield touches both left , right edges of view). instead, if try give textfield fixed width while creating, width doesn't expand/stretch user types in.
what want achieve starting width of textfield 0, , having static uilabel
s on each sides "hello "[textfield]" world"
; user types in, increasing/stretching textfield's width both left , right (as it's textaligned center). , textfield's width stretches, push uilabel
's towards edge.. so:
| ["hello "][textfield][" world"] | | ["hello "][mytextfieldtextisnice][" world"] |
what proper way of achieving without using storyboard , programatically instantiating uitextfield
, uilabel
s? how can create auto-resizing textfield user types in pushes uilabels on sides?
i use kind of situation,using storyboard
, both side of uitextfield
use uilabel
center alignment.
below screenshot of storyboard
.
then doing delegate of uitextfield
, uses following code.
-(bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string { nsstring *strforwholestring = [nsstring stringwithformat:@"%@%@",textfield.text,string]; cgsize fontsize = [strforwholestring sizewithattributes: @{nsfontattributename: [uifont fontwithname:@"helvetica" size:14]}]; if (self.textfieldlayoutwidthconstraint.constant >= 40) { self.textfieldlayoutwidthconstraint.constant = fontsize.width + 40 ; [self.view layoutifneeded]; [self.view setneedsupdateconstraints]; } return yes; }
swift code
func textfield(textfield: uitextfield!, shouldchangecharactersinrange range: nsrange, replacementstring string: string!) -> bool { let strforwholestring = nsstring(format:"%@%@", textfield.text!,string) string let fontsize: cgsize = strforwholestring.sizewithattributes([nsfontattributename: uifont.systemfontofsize(14.0)]) if self.textfieldlayoutwidthconstraint?.constant >= 40 { self.textfieldlayoutwidthconstraint!.constant = fontsize.width + 40 ; self.view.layoutifneeded(); self.view.setneedsupdateconstraints(); } return true }
may helps lot.
you can download sample code here - objective c
you can download sample code here - swift
output
Comments
Post a Comment