视图
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了视图相关的知识,希望对你有一定的参考价值。
我想创建一个插入单元accesoryView中的badgeView。我知道过去曾经有过很多这样的问题,但那些github子类似乎已经过时,无法移植到一个快速的项目中。在快速项目中,在ios中最简单的方法是什么?
像这样的东西:
答案
以下代码已在iOS7和iOS8中进行测试,其工作原理如下:
- 如果count> 0,它将以白色文本显示计数,并在其周围带有红色徽章。
- 如果count = 0,它将显示一个简单的披露指标。
- (void)updateTableViewCell:(UITableViewCell *)cell forCount:(NSUInteger)count
// Count > 0, show count
if (count > 0)
// Create label
CGFloat fontSize = 14;
UILabel *label = [[UILabel alloc] init];
label.font = [UIFont systemFontOfSize:fontSize];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor redColor];
// Add count to label and size to fit
label.text = [NSString stringWithFormat:@"%@", @(count)];
[label sizeToFit];
// Adjust frame to be square for single digits or elliptical for numbers > 9
CGRect frame = label.frame;
frame.size.height += (int)(0.4*fontSize);
frame.size.width = (count <= 9) ? frame.size.height : frame.size.width + (int)fontSize;
label.frame = frame;
// Set radius and clip to bounds
label.layer.cornerRadius = frame.size.height/2.0;
label.clipsToBounds = true;
// Show label in accessory view and remove disclosure
cell.accessoryView = label;
cell.accessoryType = UITableViewCellAccessoryNone;
// Count = 0, show disclosure
else
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
另一答案
我在cellForRowAtIndexPath中使用了这段代码
var accesoryBadge = UILabel()
var string = "2"
accesoryBadge.text = string
accesoryBadge.textColor = UIColor.whiteColor()
accesoryBadge.font = UIFont(name: "Lato-Regular", size: 16)
accesoryBadge.textAlignment = NSTextAlignment.Center
accesoryBadge.layer.cornerRadius = 4
accesoryBadge.clipsToBounds = true
accesoryBadge.frame = CGRectMake(0, 0, WidthForView(string, font: UIFont(name: "Lato-Light", size: 16), height: 20)+20, 20)
cell.accessoryView = accesoryBadge
另一答案
在Swift 4中
extension UITableViewCell
func update(count: Int)
// Count > 0, show count
if count > 0
// Create label
let fontSize: CGFloat = 14
let label = UILabel()
label.font = UIFont.systemFont(ofSize: fontSize)
label.textAlignment = .center
label.textColor = UIColor.white
label.backgroundColor = UIColor.red
// Add count to label and size to fit
label.text = "\(NSNumber(value: count))"
label.sizeToFit()
// Adjust frame to be square for single digits or elliptical for numbers > 9
var frame: CGRect = label.frame
frame.size.height += CGFloat(Int(0.4 * fontSize))
frame.size.width = (count <= 9) ? frame.size.height : frame.size.width + CGFloat(Int(fontSize))
label.frame = frame
// Set radius and clip to bounds
label.layer.cornerRadius = frame.size.height / 2.0
label.clipsToBounds = true
// Show label in accessory view and remove disclosure
self.accessoryView = label
self.accessoryType = .none
else
self.accessoryView = nil
self.accessoryType = .disclosureIndicator
以上是关于视图的主要内容,如果未能解决你的问题,请参考以下文章