最新消息:20210917 已从crifan.com换到crifan.org

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

Swift crifan 3292浏览 0评论

[已解决]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

即可。

转载请注明:在路上 » [已解决]Swift中子View如何设置在父级View的对齐方式

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
94 queries in 0.186 seconds, using 23.27MB memory