I want to apply the frame of UILabel to iphone6 and iphone6plus by code.

Asked 2 years ago, Updated 2 years ago, 82 views

I made parts other than UILabel on the storyboard and applied AutoLayout on the storyboard, but I have no choice but to generate UILabel with code, so when it comes to iphone6 and iphone6 plus, it is out of position.Default iphone5 is in a normal position.
Is there a way to generate the UILabel generated by the code in the ideal position for iPhone6 and iphone6plus?I would appreciate it if you could explain it in a sample.

ios swift autolayout uilabel

2022-09-30 21:14

1 Answers

Setting Auto Layout from code to the UILabel generated by code is a normal workaround.With this method, you can do everything you can with Auto Layout in the same way.However, the disadvantage is that it is a little troublesome to use the code.

The only way to deal with this is to place a dummy view where you want to place the UILabel.

Set Auto Layout in the dummy View to meet the UILabel location and size that you ultimately need.From the code, addSubview UILabel to that View.

Now that the UILabel position is based on the dummy View position, I think we can deal with the misalignment issue. (Autoresizing Mask can also handle the size.)

This is what the code looks like.

class ViewController:UIViewController {

    /// Dummy View in UILabel Position
    @IBOutletweak varbaseView:UIView!

    override func viewDidLoad(){
        super.viewDidLoad()

        /// Generate UILabel from code
        letre = CGRect (x:10, y:10, width:200, height:60)
        let label = UILabel (frame:re)
        label.text = "Test label"
        baseView.addSubview(label)
    }
}


2022-09-30 21:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.