[已解决]Swift中子View如何设置在父级View的对齐方式

[已解决]Swift中的UITableView中自定义UITableViewCellAccessoryType

期间,需要去:

对于cell的accessory的view中的:

上面的label

下面的image

两个view,设置子view在父view(accessory)中的对齐方式:

比如靠左或靠右对齐。

 

[折腾过程]

1.搜:

swift sub view align in parent view

swift subview align in parent view

参考:

iphone – How to center a subview of UIView – Stack Overflow

去试试:

	preventDisturbIconView.center = CGPointMake(
	(cell.accessoryView?.bounds.size.width)!/2,
	preventDisturbIconView.bounds.size.height/2 + lastPublishTimeText.frame.size.height)

好像是起到居中对齐的效果了:

accessory show align center of cell

然后再去:

让下面的图片右对齐:

搜:

swift subview align right in parent view

参考:

cocoa – How to align a subview to the center of a parent NSView – Stack Overflow

http://stackoverflow.com/questions/4681176/how-to-align-a-subview-to-the-center-of-a-parent-nsview

感觉好像是:

此处的,想要subview:

        let preventDisturbIconView = UIImageView(image:UIImage(named:"prevent_disturb_16x24.png"))
        preventDisturbIconView.frame = CGRectMake(
            0, //32,
            CGFloat(rowHeight)/2, //24,
            //preventDisturbIconView.bounds.size.width,
            (cell.accessoryView?.bounds.size.width)!,
            //preventDisturbIconView.bounds.size.height)
            CGFloat(rowHeight)/2)

没法直接用align的方式去在父view:

        cell.accessoryView?.addSubview(preventDisturbIconView)

去右对齐了。

看来只能是自己去计算x的坐标了:

//        //both align center of accessory
//        lastPublishTimeText.textAlignment = NSTextAlignment.Center
//        preventDisturbIconView.center = CGPointMake(
//            (cell.accessoryView?.bounds.size.width)!/2,
//            preventDisturbIconView.bounds.size.height/2 + lastPublishTimeText.frame.size.height)
       
        //both align right of accessory
        lastPublishTimeText.textAlignment = NSTextAlignment.Right
        preventDisturbIconView.frame.origin.x = (cell.accessoryView?.bounds.size.width)! - preventDisturbIconView.bounds.size.width

效果是:

effect of calc x position

 

[总结]

子view在父view中:

(1)居中对齐的话,是可以用center的:

subView.center = CGPointMake(parentView.bounds.size.width/2,parentView.bounds.size.height/2)

(2)右对齐的话:是没有api或属性可以设置的,只能自己去计算x的位置了:

subView.frame = CGRectMake(xx,xx,xx,xx)
subView.frame.origin.x = parentView.bounds.size.width - subView.bounds.size.width

即可。



发表评论

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

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