[ SWIFT ] - 動態產生物件

@IBOutlet weak var myscroll: UIScrollView!
@IBOutlet weak var myimg: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //動態產生UIImageView
        var img1 = UIImageView(image: UIImage(named: "8.jpeg"))
        var img2 = UIImageView(image: UIImage(named: "9.jpg"))
        var img3 = UIImageView(image: UIImage(named: "10.jpg"))

        img1.contentMode = UIViewContentMode.ScaleAspectFit
        img2.contentMode = UIViewContentMode.ScaleToFill
        img3.contentMode = UIViewContentMode.ScaleAspectFill
        
        var rect = CGRect()
        rect = self.myscroll.frame
        img1.frame = rect
        img2.frame = CGRectOffset(img1.frame, img1.frame.size.width, 0)
        img3.frame = CGRectOffset(img2.frame, img2.frame.size.width, 0)
        
        var size = CGSizeMake(img1.frame.size.width + img1.frame.size.width + img1.frame.size.width, rect.origin.y)
        
        self.myscroll.contentSize = size
        

        self.myscroll.addSubview(img1)

//動態產生Button
let button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
        button.frame = CGRectMake(50, 50, 100, 30)
        button.backgroundColor = UIColor.greenColor()
        button.setTitle("Hellow World", forState: UIControlState.Normal)
        button.addTarget(self, action: "buttonPress:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)

留言

熱門文章