[已解决]Swift给UITableViewCell中的imageView的addSubview一个label且是中心对齐

已有代码:

            let headerLabel = UILabel(frame: CGRectMake(
0,
0,
drawedCustomHeaderImage.size.width,
drawedCustomHeaderImage.size.height))
headerLabel.font = FONT_CONVERSATION_HEADER
headerLabel.textColor = UIColor.whiteColor()
headerLabel.text="简"

cell.imageView?.addSubview(headerLabel)

效果是:

existed label align left inside image view

现在希望是:
简 字,和imageView中心对齐
搜:
swift imageView subview center
参考:
试了半天:
            //headerLabel.frame.origin.x += drawedCustomHeaderImage.size.width/2
            //headerLabel.frame.origin.x += SIZE_CONVERSATION_HEADER/2
            //headerLabel.center = (cell.imageView?.center)!
            //headerLabel.frame.origin.x =
            //print("cell.imageView?.center=\(cell.imageView?.center)") //cell.imageView?.center=Optional((0.0, 0.0))
            //print("cell.imageView?.frame=\(cell.imageView?.frame)") //cell.imageView?.frame=Optional((0.0, 0.0, 0.0, 0.0))
            //headerLabel.center = (headerLabel.superview?.center)!
            //headerLabel.center = (cell.imageView?.convertPoint((cell.imageView?.center)!, fromView: cell.imageView?.superview))!
都不行。
 搜:
swift UITableViewCell imageView subview alignment
参考:
最后加了:
            headerLabel.textAlignment = NSTextAlignment.Center
变成:
            let headerLabel = UILabel(frame: CGRectMake(
                0,
                0,
                drawedCustomHeaderImage.size.width,
                drawedCustomHeaderImage.size.height))
            headerLabel.font = FONT_CONVERSATION_HEADER
            headerLabel.textColor = UIColor.whiteColor()
            headerLabel.text = "简"
            headerLabel.textAlignment = NSTextAlignment.Center
            cell.imageView?.addSubview(headerLabel)

就可以了:

label text align center of image view of cell

[总结]

label对于父视图的对齐,默认是左对齐Left

想要设置为居中对齐,则可以设置为:

headerLabel.textAlignment = NSTextAlignment.Center

即可。



发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量