objective c - How can I tell NSTextField to autoresize it's font size to fit it's text? -
this question has answer here:
- get nstextfield contents scale 1 answer
looking whatever cocoa equivalent of [uilabel adjustsfontsizetofitwidth]
is.
i've solved creating nstextfieldcell subclass overrides string drawing. looks whether string fits , if doesn't decreases font size until fit. made more efficient , have no idea how it'll behave when cellframe
has width of 0. nevertheless enough™ needs.
- (void)drawinteriorwithframe:(nsrect)cellframe inview:(nsview *)controlview { nsattributedstring *attributedstring; nsmutableattributedstring *mutableattributedstring; nssize stringsize; nsrect drawrect; attributedstring = [self attributedstringvalue]; stringsize = [attributedstring size]; if (stringsize.width <= cellframe.size.width) { // string small enough. skip sizing. goto drawstring; } mutableattributedstring = [attributedstring mutablecopy]; while (stringsize.width > cellframe.size.width) { nsfont *font; font = [mutableattributedstring attribute:nsfontattributename atindex:0 effectiverange:null ]; font = [nsfont fontwithname:[font fontname] size:[[[font fontdescriptor] objectforkey:nsfontsizeattribute] floatvalue] - 0.5 ]; [mutableattributedstring addattribute:nsfontattributename value:font range:nsmakerange(0, [mutableattributedstring length]) ]; stringsize = [mutableattributedstring size]; } attributedstring = [mutableattributedstring autorelease]; drawstring: drawrect = cellframe; drawrect.size.height = stringsize.height; drawrect.origin.y += (cellframe.size.height - stringsize.height) / 2; [attributedstring drawinrect:drawrect]; }
Comments
Post a Comment