最新消息:VPS服务器又从fzhost.net换回Linode了,主题仍用朋友推荐的大前端D8

[未解决]swift中UIView初始化如何实现自动布局

Swift crifan 118浏览 0评论

想要自定义个UIView

想要支持自动布局

-》所以就不打算初始化frame

-》但是导致init函数就没法写

-》最后就只好写成了:

class SearchPhoneView: UIView, UITextFieldDelegate {
    var searchImageView:UIImageView
    var searchTextField:UITextField
    init(){
        self.searchImageView = UIImageView(image: UIImage(named: "search_phone"))
        self.searchTextField = UITextField()
        super.init(frame: CGRectZero)
       

别处调用是:

var searchPhoneView:SearchPhoneView
    init(){
        self.searchPhoneView = SearchPhoneView()
        super.init(nibName: nil, bundle: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
       
        self.view.backgroundColor = ColorAppBackground
        self.view.addSubview(self.searchPhoneView)

-》导致后续UI不显示。。。

搜:

swift uiview custom autolayout

ios – How to set constraints for a reusable UIView in Swift with auto layout? – Stack Overflow

Writing a Custom Control for iOS 8 using Swift and Auto Layout – Coursera Technology

Custom Live Views and Auto Layout — Swift + iOS 9 Development Training

Storyboard和Code加载Xib自定义View

改为了:

    override init(frame: CGRect) {
        self.searchImageView = UIImageView(image: UIImage(named: "search_phone"))
        self.searchTextField = UITextField()
//        super.init(frame: CGRectZero)
        super.init(frame: frame)

结果还是不显示。。。

swift custom UIView not show

ios – Swift custom control is not showing when being used in view controller (code attached) – Stack Overflow

Custom uiview class not showing data after setNeedsDisplay called inside uitableviewcell Swift – Stack Overflow

ios – Custom UIView not showing up when added as subview – Stack Overflow

ios – Adding and changing a custom UIView programmatically (Swift) – Stack Overflow

后来看了下面的内容:

searchPhoneView.searchTextField=<UITextField: 0x7b6aa370; frame = (0 0; 0 0); text = ‘18168978839’; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7b6aa530>>
searchPhoneView.searchTextField.placeholder=Optional("搜索手机号")
searchPhoneView.searchImageView=<UIImageView: 0x7b6aa260; frame = (0 0; 20 20); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7b6aa340>> – (null)

基本明白了:

主要是由于,没有设置frame的大小,导致内部的各种子view,没法显示。。。

结果是猜错了:

       self.view.addSubview(self.searchPhoneView)
        searchPhoneView.frame = CGRectMake(0, 0, self.view.frame.width 20, 68)
//        constrain(searchPhoneView) { searchPhoneView in
//            searchPhoneView.top == searchPhoneView.superview!.top + 10
//            searchPhoneView.width == searchPhoneView.superview!.width – 20
//            searchPhoneView.height == 48
//            searchPhoneView.centerX == searchPhoneView.superview!.centerX
//        }

还是不显示。

抽空再继续去弄吧。。。

转载请注明:在路上 » [未解决]swift中UIView初始化如何实现自动布局

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
16 queries in 0.192 seconds, using 9.90MB memory