我的 OS X 应用程序需要类似的东西。他们在那里使用名为NSTokenField 的东西,但不幸的是,iOS 平台上没有类似的东西。因此,您基本上只能创建自己的令牌或使用现有的第三方库。如果您需要有关如何创建自定义令牌的详细信息,请告诉我。
附:创建自定义标记需要覆盖 drawRect 方法和一些贝塞尔路径的使用。
扩展答案:
我将向您展示如何在 NSTextView(包含文本,但也可以包含 NSTextAttachment)上创建标记。此外,代码可以在 Cocoa 上运行(但只需稍加调整,同样可以在 Cocoa Touch 中实现。
1.) 创建扩展NSTextAttachmentCell的类
2.) 覆盖方法-(void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
[self drawWithFrame:cellFrame inView:controlView characterIndex:NSNotFound layoutManager:nil];
}
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView characterIndex:(NSUInteger)charIndex layoutManager:(NSLayoutManager *)layoutManager 的实现是这样的:
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView characterIndex:(NSUInteger)charIndex layoutManager:(NSLayoutManager *)layoutManager
{
NSColor* bgColor = [NSColor redColor];
NSColor* borderColor = [NSColor blackColor];
NSRect frame = cellFrame;
CGFloat radius = ceilf([self cellSize].height / 2.f);
NSBezierPath* roundedRectanglePath = [NSBezierPath bezierPathWithRoundedRect: NSMakeRect(NSMinX(frame) + 0.5, NSMinY(frame) + 3.5, NSWidth(frame) - 1, NSHeight(frame) - 1) xRadius: radius yRadius: radius];
[bgColor setFill];
[roundedRectanglePath fill];
[borderColor setStroke];
[roundedRectanglePath setLineWidth: 1];
[roundedRectanglePath stroke];
CGSize size = [[self stringValue] sizeWithAttributes:@{NSFontAttributeName:defaultFont}];
CGRect textFrame = CGRectMake(cellFrame.origin.x + (cellFrame.size.width - size.width)/2,
cellFrame.origin.y + 2.f,
size.width,
size.height);
[[self stringValue] drawInRect:textFrame withAttributes:@{NSFontAttributeName:defaultFont, NSForegroundColorAttributeName: [NSColor whiteColor]}];
}
所有代码都应该是不言自明的,但是如果您有任何问题,请提出。希望对您有所帮助。