iPhone Development- Resizng Uilabel 및 Custom UabiteViewCell에 대한 또 다른 질문
-
19-09-2019 - |
문제
일부 프로젝트에서 다음 기능을 사용했지만 최근에는 작은 예제를 만들었습니다. 신뢰할 수 없습니다 (적어도 어떤 상황에서는) :
[NSString sizeWithFont:font constrainedToSize:size]
[NSString sizeWithFont:font constrainedToSize:size lineBreakMode:lineBreak]
나는 iPhone의 사진 앨범 응용 프로그램, 즉 앨범 이름과 앨범의 사진 수와 함께 볼 수있는 결과를 달성하기 위해 사용자 정의 UitableViewCell 클래스를 만들었습니다. 위의 함수를 사용하여 세부 텍스트를 조정했습니다 (count). 코드는 다음과 같습니다.
Interface File:
#import <UIKit/UIKit.h>
@interface CustomValue2Cell : UITableViewCell {
UIImageView *cellImage;
UILabel *cellTextLabel;
UILabel *cellDetailTextLabel;
}
@property (nonatomic, retain) UIImageView *cellImage;
@property (nonatomic, retain) UILabel *cellTextLabel;
@property (nonatomic, retain) UILabel *cellDetailTextLabel;
- (void)setCellImage:(UIImage *)image withText:(NSString *)text andDetail:(NSString *)detail;
- (CGSize)getSizeOfText:(NSString *)text withFont:(UIFont *)font;
@end
Implementation File:
#import "CustomValue2Cell.h"
@implementation CustomValue2Cell
@synthesize cellImage;
@synthesize cellTextLabel;
@synthesize cellDetailTextLabel;
// Coordinate positions of Image, Text Label, and Detail Text Label
# define kImageXPosition 3
# define kImageYPosition 3
# define kImageWidth 37.0
# define kImageHeight 37.0
# define kTextXPosition 55
# define kTextYPosition 10
# define kTextWidth 200
# define kTextHeight 22
# define kDetailXPosition 55
# define kDetailYPosition 10
# define kDetailWidth 40
# define kDetailHeight 22
// Displacement value for Text Label with Detail Text Label
// Displacement value of 10-15 works with non-bold font
# define kCellSubviewDisplacement 20
// Label Font Size for Text Label and Detail Text Label
# define kTextLabelFontSize 18
# define kDetailLabelFontSize 16
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
// Color and font for the main label
UIColor *textLabelColor = [UIColor blackColor];
UIFont *textLabelFont = [UIFont systemFontOfSize:kTextLabelFontSize];
// Color and font for the detail label
UIColor *detailTextColor = [UIColor darkGrayColor];
UIFont *detailTextFont = [UIFont systemFontOfSize:kDetailLabelFontSize];
// Highligted row color
UIColor *highlightedTextColor = [UIColor whiteColor];
// Define boundary of the cell contents
CGRect rect;
// Set properties of Image Thumbnail
rect = CGRectMake(kImageXPosition, kImageYPosition, kImageWidth, kImageHeight);
cellImage = [[UIImageView alloc] initWithFrame:rect];
// Set properties of Name
rect = CGRectMake(kTextXPosition, kTextYPosition, kTextWidth, kTextHeight);
cellTextLabel = [[UILabel alloc] initWithFrame:rect];
[cellTextLabel setFont:textLabelFont];
[cellTextLabel setTextColor:textLabelColor];
[cellTextLabel setHighlightedTextColor:highlightedTextColor];
// Set properties of Value
rect = CGRectMake(kDetailXPosition, kDetailYPosition, kDetailWidth, kDetailHeight);
cellDetailTextLabel = [[UILabel alloc] initWithFrame:rect];
[cellDetailTextLabel setFont:detailTextFont];
[cellDetailTextLabel setTextColor:detailTextColor];
[cellDetailTextLabel setHighlightedTextColor:highlightedTextColor];
// Put Image, Name, and Value in Content View
[[self contentView] addSubview:cellImage];
[[self contentView] addSubview:cellTextLabel];
[[self contentView] addSubview:cellDetailTextLabel];
//Set cell selection style (Blue)
self.selectionStyle = UITableViewCellSelectionStyleBlue;
}
return self;
}
- (void)setCellImage:(UIImage *)image withText:(NSString *)text andDetail:(NSString *)detail {
cellImage.image = image;
cellTextLabel.text = text;
cellDetailTextLabel.text = detail;
// Get an estimated size of text in the label,
// which will be used to estimate the position of detail label
UIFont *textLabelFont = [UIFont systemFontOfSize:kTextLabelFontSize];
CGSize size = [self getSizeOfText:text withFont:textLabelFont];
// Re-set the frame of detail view
CGRect frame = CGRectMake(kDetailXPosition, kDetailYPosition, kDetailWidth, kDetailHeight);
frame.origin.x = frame.origin.x + size.width + kCellSubviewDisplacement;
[cellDetailTextLabel setFrame:frame];
}
- (CGSize)getSizeOfText:(NSString *)text withFont:(UIFont *)font {
return [text sizeWithFont:font constrainedToSize:CGSizeMake(kTextWidth, kTextHeight)];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc {
[cellImage release];
[cellTextLabel release];
[cellDetailTextLabel release];
[super dealloc];
}
@end
내 커스텀 클래스를 테스트하기 위해 글꼴 목록을 준비하고 테이블보기에 표시했습니다. 사용 가능한 글꼴 목록을 얻기위한 코드 :
fontFamily = [[NSMutableArray alloc] initWithArray:[UIFont familyNames]];
fonts = [[NSMutableArray alloc] init];
for(NSUInteger i=0; i<[fontFamily count]; i++) {
NSString *familyName = [fontFamily objectAtIndex:i];
NSArray *array = [UIFont fontNamesForFamilyName:familyName];
[fonts addObjectsFromArray:array];
}
셀을 반환하는 코드는 다음과 같습니다.
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
CGRect rect = CGRectMake(0.0, 0.0, 320.0, 50.0);
CustomValue2Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomValue2Cell alloc] initWithFrame:rect reuseIdentifier:CellIdentifier] autorelease];
}
NSString *font = [fonts objectAtIndex:indexPath.row];
NSString *detail = [NSString stringWithFormat:@"%d", [[fonts objectAtIndex:indexPath.row] length]];
[cell setCellImage:[UIImage imageNamed:@"Pointy.gif"] withText:font andDetail:detail];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]
return cell;
}
Result: Text Label and Detail Text Label are overlapping for some values. e.g. "CouierNewPS-BoldMT" and "25" overlap each other, and in some other cases, they are not overlapping but they are very close.
Question: Is their a better alternative to -sizeWithFont function? Or, am i doing something very stupid to mess things up?
긴 게시물에 대해 죄송합니다. 모든 도움이 감사합니다. 기대에 감사합니다.
해결책
글쎄, 당신은 실제로 문제가 무엇인지 정확히 말하지 않습니다. 너무 큰 크기를 너무 크고, 너무 작고, 한 줄에, 아니면 완전히 다른 것입니까?
스트링 사이징을 할 때 사용합니다
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
지정하십시오 UILineBreakModeWordWrap
라인 브레이크 모드의 경우. 이것이 본질적으로 동일한 값을 반환하는지 확실하지 않지만, 나는 그것이 나를 위해 효과가있는 것을 발견했습니다.
다른 팁
cgsize 크기, 제한된 크기;
Constriandsize.width = maxfloat; 제한된 size.height = maxfloat;
size = [Text SizeWithFont : SystemFontOfSize : 14 제약 조건 : 제한된 규모 라인 브레이크 모드];
반환 된 제약 크기는 텍스트의 정확한 너비/높이를 가져야합니다.
이 기능과 비슷한 문제가 있었고 여러 번 디버깅을 한 후에는 레이블 너비보다 너비를 매개 변수 ConstrataintOsize로 전달하면 모든 경우에 작동한다고 생각했습니다.
아래를 시도하십시오
- (CGSize)getSizeOfText:(NSString *)text withFont:(UIFont *)font {
return [text sizeWithFont:font constrainedToSize:CGSizeMake(kTextWidth - 10, kTextHeight)];
}
또한 uilinebreakmode의 값으로 uilinebreakmodewordwrap을 사용하십시오