ios 如何在 UITableView 中将 UITableViewCell 图像更改为圆形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23350728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change UITableViewCell Image to Circle in UITableView
提问by Luke Irvin
My code works for the most part.
我的代码大部分都有效。
- The issue I am having is the images start out as square, and change to circle when I scroll the table or refresh it.
- 我遇到的问题是图像以方形开始,当我滚动表格或刷新表格时更改为圆形。
What am I missing?
我错过了什么?
Here's my code:
这是我的代码:
cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2.0;
cell.imageView.layer.borderWidth = 3.0;
cell.imageView.layer.borderColor = [UIColor colorWithRed:157.0/255.0 green:34.0/255.0 blue:53.0/255.0 alpha:1.0]
.CGColor;
cell.imageView.clipsToBounds = YES;
NSDictionary *tweet = (self.results)[indexPath.row];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * imageString = [tweet valueForKeyPath:@"user.profile_image_url"];
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:imageString]];
if (imageData != nil)
{
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData: imageData];
[cell setNeedsLayout];
});
}
});
EDIT---- The code is in cellForRowAtIndexPath
编辑----代码在 cellForRowAtIndexPath
- Right when I launch the app the cell images are square. If I pullToRefresh the change to round or if I start scrolling the table they change to round.
- 当我启动应用程序时,单元格图像是方形的。如果我 pullToRefresh 更改为圆形,或者如果我开始滚动表格,它们将更改为圆形。
EDIT TWO
编辑两个
Another issue I am seeing is the images change as I scroll.
我看到的另一个问题是图像在滚动时会发生变化。
How do I prevent this?
我如何防止这种情况?
回答by Siavash Alp
In order if anyone having this problem, here is the solution in
为了如果有人遇到这个问题,这里是解决方案
Swift
迅速
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:ContactCellTableViewCell? = tableView.dequeueReusableCellWithIdentifier("contactCell", forIndexPath: indexPath) as? ContactCellTableViewCell
var contact : ContactStruct
image = searchResults[indexPath.row]
let newImage = resizeImage(image, toTheSize: CGSizeMake(70, 70))
var cellImageLayer: CALayer? = cell?.imageView.layer
cellImageLayer!.cornerRadius = 35
cellImageLayer!.masksToBounds = true
cell?.imageView.image = newImage
return cell!
}
As you might noticed the 35hardcode is basically half of the image size which is 70in here. And here is the resize function:
正如您可能注意到的,35硬编码基本上是图像大小的一半,这里是70。这是调整大小功能:
func resizeImage(image:UIImage, toTheSize size:CGSize)->UIImage{
var scale = CGFloat(max(size.width/image.size.width,
size.height/image.size.height))
var width:CGFloat = image.size.width * scale
var height:CGFloat = image.size.height * scale;
var rr:CGRect = CGRectMake( 0, 0, width, height);
UIGraphicsBeginImageContextWithOptions(size, false, 0);
image.drawInRect(rr)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return newImage
}
Note: I am using a custom cell class as below:
注意:我正在使用自定义单元类,如下所示:
import UIKit
class ContactCellTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var contactImage: UIImageView!
@IBOutlet weak var phoneLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
It really took me a while to figure this one out. The images become rounded after scrolling at first, but now using this code you are going to have the rounded images inside the cell from beginning. Hope it helped anyone.
我真的花了一段时间才弄明白这个问题。最初滚动后图像变得圆润,但现在使用此代码,您将从一开始就在单元格内拥有圆润的图像。希望它帮助任何人。
回答by Binoy jose
Try this in override-
试试这个覆盖 -
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// image Width(84) / 2 = 42
cell.CellImage.layer.cornerRadius = 42.0
cell.CellImage.layer.masksToBounds = true
//or
cell.CellImage.layer.cornerRadius = cell.CellImage.frame.width / 2
cell.CellImage.clipsToBounds = true
}
回答by rmaddy
Most likely the cell's frame (and hence the imageView's frame) isn't set the very first time the cell is created. So setting the imageView's layer's cornerRadius
based on that initial frame doesn't work. The best solution is to implement the tableView:willDisplayCell:forRowAtIndexPath:
delegate method and set the layer there:
很可能在第一次创建单元格时没有设置单元格的框架(因此也没有设置 imageView 的框架)。因此,cornerRadius
根据该初始帧设置 imageView 的图层不起作用。最好的解决方案是实现tableView:willDisplayCell:forRowAtIndexPath:
委托方法并在那里设置层:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2.0;
}
回答by rdelmar
Create a custom cell, and add an image view (with an IBOutlet), sized and positioned however you want (the outlet is "iv" in my example below). Put the code to make image view round in the awakeFromNib method (assuming your cell is created in a nib or storyboard).
创建一个自定义单元格,并添加一个图像视图(带有 IBOutlet),根据需要调整大小和位置(在我下面的示例中,插座是“iv”)。将代码放在awakeFromNib 方法中使图像视图变圆(假设您的单元格是在笔尖或故事板中创建的)。
-(void)awakeFromNib {
self.iv.layer.cornerRadius = self.iv.frame.size.width / 2.0;
self.iv.layer.borderWidth = 3.0;
self.iv.layer.borderColor = [UIColor colorWithRed:157.0/255.0 green:34.0/255.0 blue:53.0/255.0 alpha:1.0].CGColor;
self.iv.clipsToBounds = YES;
}
回答by Rajesh Loganathan
Its simple..
这很简单..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.ImageView.layer.cornerRadius = 150.0f;
cell.ImageView.layer.borderWidth = 2.0f;
cell.ImageView.layer.borderColor = [UIColor blackColor].CGColor;
cell.ImageView.clipsToBounds = YES;
}
Refer this link for more information: http://ios-blog.co.uk/tutorials/quick-tips/how-to-create-rounded-avatars-in-your-ios-application/
有关更多信息,请参阅此链接:http: //ios-blog.co.uk/tutorials/quick-tips/how-to-create-rounded-avatars-in-your-ios-application/
回答by Elliott Davies
I had a similar issue, my UIImageView was initially a square and would only show as circular when the UITableViewCell it was within was either highlighted or selected.
我有一个类似的问题,我的 UIImageView 最初是一个正方形,只有当它所在的 UITableViewCell 被突出显示或被选中时才会显示为圆形。
It was a simple fix:
这是一个简单的修复:
Swift 2.0
斯威夫特 2.0
imgView.layer.cornerRadius = imgView.frame.width / 2
imgView.clipsToBounds = true
This was placed inside the awakeFromNib() for my custom UITableViewCell.
这被放置在我的自定义 UITableViewCell 的awakeFromNib() 中。
This is assuming imgView is the name of the UIImageView hooked up via storyboard inside this custom UITableViewCell.
这是假设 imgView 是通过此自定义 UITableViewCell 内的故事板连接的 UIImageView 的名称。
回答by dreamer.psp
Set the image view to a circle inside the async call where you set the image.
将图像视图设置为设置图像的异步调用内的圆圈。
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * imageString = [tweet valueForKeyPath:@"user.profile_image_url"];
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:imageString]];
if (imageData != nil)
{
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData: imageData];
cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2.0;
cell.imageView.layer.borderWidth = 3.0;
cell.imageView.layer.borderColor = [UIColor colorWithRed:157.0/255.0 green:34.0/255.0 blue:53.0/255.0 alpha:1.0]
.CGColor;
cell.imageView.clipsToBounds = YES;
[cell setNeedsLayout];
});
}
});
回答by Roman Solodyashkin
@interface MyCell : UITableViewCell
@end
@implementation MyCell
- (void)awakeFromNib
{
[super awakeFromNib];
self.imageView.layer.masksToBounds = YES;
self.textLabel.font = [UIFont systemFontOfSize:17];
self.textLabel.textColor = [UIColor darkTextColor];
}
// --- image view frame is empty rect inside tableView: willDisplayCell:
// +++ set cornerRadius inside layoutSubviews works.
- (void)layoutSubviews
{
[super layoutSubviews];
// layout image view
CGRect vfr = self.frame;
CGRect imgvr = self.imageView.frame;
imgvr.origin.x = 16;
imgvr.size.width = CGRectGetHeight(vfr);
self.imageView.frame = imgvr;
// update corner radius
self.imageView.layer.cornerRadius = imgvr.size.width * 0.5f;
// layout label
CGRect lblr = self.textLabel.frame;
lblr.origin.x = CGRectGetMaxX(imgvr) + 16;
lblr.size.width = CGRectGetWidth(vfr) - CGRectGetMaxX(imgvr) - 32;
self.textLabel.frame = lblr;
}
@end
回答by Sergey Di
In case your cell is by code:
如果您的单元格是通过代码:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let myImageView = (cell as! MyCustomCell).myImageView
myImageView.layoutIfNeeded()
myImageView.layer.cornerRadius = myImageView.frame.width / 2.0
}
回答by tuwilof
cell.imageView?.layer.cornerRadius = 22.0
cell.imageView?.layer.masksToBounds = true