当前位置: 代码迷 >> 综合 >> 【Cocoa】cocoa UI 常用算法
  详细解决方案

【Cocoa】cocoa UI 常用算法

热度:42   发布时间:2023-12-08 08:57:07.0

1. 计算字符串高度

- (void)resizeTextField:(NSTextField *)textField withAttributeString:(NSAttributedString *)attrStr andFixedWidth:(float)fixedWidth
{[textField setAttributedStringValue:attrStr];NSTextFieldCell *cell = [textField cell];[textField setStringValue:[attrStr string]];float textFieldHeight = [cell cellSizeForBounds:NSMakeRect(0, 0, fixedWidth, FLT_MAX)].height;[textField setStringValue:@""];textField.frame = NSMakeRect(textField.frame.origin.x, textField.frame.origin.y, fixedWidth, textFieldHeight);
}

-(void)setWarningText:(NSString*)text
{[textField setStringValue:text];NSSize textSize = NSZeroSize;if (textField.stringValue.length > 0) {NSRange range;NSDictionary* atribute = [[textField attributedStringValue] attributesAtIndex:0 effectiveRange:&range];textSize = [textField.stringValue  boundingRectWithSize:NSMakeSize(textField.frame.size.width, 600) options:NSStringDrawingUsesLineFragmentOrigin attributes:atribute].size;}NSRect frame = self.frame;int textHeight = (((textSize.height == 0) ? TOOL_SIZE : textSize.height)+ DELOREAN_GAP * 2);frame.origin.y += frame.size.height - textHeight;frame.size.height = textHeight;self.frame = frame;}

[注]boundingRectWithSize:NSMakeSize(textField.frame.size.width, 600) 中600是随意的数字,最高不超过这个值


NSSize getTextLayoutByWidthAndFont(NSString* string, float width, NSFont* font)
{NSSize containerSize;containerSize.width = width;containerSize.height = FLT_MAX;//NSRange	textRange;NSTextStorage* textStorage = [[NSTextStorage alloc] init];NSTextContainer* textContainer = [[NSTextContainer alloc] initWithContainerSize:containerSize];NSLayoutManager* textLayoutManager = [[NSLayoutManager alloc] init];[textLayoutManager addTextContainer:textContainer];[textStorage addLayoutManager:textLayoutManager];[textContainer setLineFragmentPadding:0.0f];NSDictionary *styles = [[[NSDictionary alloc] initWithObjectsAndKeys:font, NSFontAttributeName,[NSColor blackColor], NSForegroundColorAttributeName,nil] autorelease];[[textStorage mutableString] setString:string];[textStorage setAttributes:styles range:NSMakeRange(0U, [string length])];[textLayoutManager glyphRangeForTextContainer:textContainer];containerSize.height = [textLayoutManager usedRectForTextContainer:textContainer].size.height;[textContainer release];[textStorage release];[textLayoutManager release];NSAttributedString* title = [[[NSAttributedString alloc] initWithString:string  attributes:styles] autorelease];containerSize.width = containerSize.width < title.size.width?containerSize.width:title.size.width+2;return containerSize;
}