2016年10月5日 星期三

CollectionViewController的應用

先在sotryboard內建立一個collectionviewcontroller
然後再建立一個繼承於UICollectionViewController的class
而此class會幫你建立好cell,但我個人將它移除後自己寫過,也可用系統建立的。
其餘不多說拉!以下看code


import UIKit


class MenuViewController: UICollectionViewController,UICollectionViewDelegateFlowLayout {

    
    override func viewDidLoad() {
        super.viewDidLoad()

      
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
        return 20
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MenuViewCell;
        
        cell.layer.cornerRadius = 10//cell圓角
        cell.nameLabel.text = "這是第\(indexPath.row)cell"
        // Configure the cell
    
        return cell
    }
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let row = indexPath.row
        print(row)
        
    }

//MARK: CELL內容

    //計算cell上下高
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        let size:CGSize = CGSize(width: self.view.frame.size.width/2-12, height: (self.view.frame.size.width/2-12)/1.5);

        return size
    }
    //計算cell上下高
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
        return 10
    }
    //計算cell左右寬度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {
        return 5
    }
    //cell上下左右留邊
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        return UIEdgeInsetsMake(10, 6, 10, 6);
    }

    

呈現出來的效果如下

2016年10月3日 星期一

註冊頁面(SWIFT3)

這邊要製作的是註冊頁面,如需登入的朋友們請到http://h81061678.blogspot.com/2016/10/swift3.html
在這跟註冊一樣使用了email格式盼斷,textfield的判斷(return動作)及監聽動作

不多說了一樣先放上code給大家參考

import UIKit

class RegisteredViewController: UIViewController,UITextFieldDelegate {
    
    @IBOutlet weak var TopView: UIView!
    @IBOutlet weak var registeredBtn: UIButton!
    @IBOutlet weak var AgreeBtn: UIButton!
    @IBOutlet weak var eMailField: UITextField!
    @IBOutlet weak var PasswordField: UITextField!
    @IBOutlet weak var PasswordCKField: UITextField!
    @IBOutlet weak var NicknameField: UITextField!
    @IBOutlet weak var BirthyearField: UITextField!
    @IBOutlet weak var BirthmonthField: UITextField!
    @IBOutlet weak var BirthdayField: UITextField!
    
    var UserDef:UserDefaults!
    var agreeCK:Bool!
    var singleFingerTap:UITapGestureRecognizer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //監聽鍵盤動作
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardWasShown), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardWasHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
        singleFingerTap = UITapGestureRecognizer.init(target: self, action: #selector(handleSingleTap));
        
        agreeCK = false;
        UserDef = UserDefaults.standard
        UserDef.set(agreeCK, forKey: "ck");
        
        AgreeBtn.layer.borderWidth = 1.5;
        AgreeBtn.layer.borderColor = UIColor(red: 77/255, green: 77/255, blue: 77/255, alpha: 1).cgColor
        registeredBtn.layer.cornerRadius = 5;
        
        self.eMailField.delegate = self;
        self.PasswordField.delegate = self;
        self.PasswordCKField.delegate = self;
        self.NicknameField.delegate = self;
        eMailField.clearButtonMode = .always;
        PasswordField.clearButtonMode = .always;
        PasswordCKField.clearButtonMode = .always;
        NicknameField.clearButtonMode = .always;
       
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
    }
    
    @IBAction func AgrddBtn(_ sender: UIButton) {
        if (UserDef.bool(forKey: "ck") == false){
            agreeCK = true;
            UserDef.set(agreeCK, forKey: "ck");
            print(UserDef.bool(forKey: "ck"))
            AgreeBtn.setBackgroundImage(UIImage(named:"tick"), for: .normal)
        }else{
            agreeCK = false;
            UserDef.set(agreeCK, forKey: "ck");
            print(UserDef.bool(forKey: "ck"))
            AgreeBtn.setBackgroundImage(UIImage(named:""), for: .normal)
            AgreeBtn.backgroundColor = UIColor.white;
        }
    }
    
    
    @IBAction func RegisteredBtn(_ sender: UIButton) {
        if(UserDef.bool(forKey: "ck")==true){
            if(eMailField.text != "" && PasswordField.text != "" && NicknameField.text != "" && BirthyearField.text != "" && BirthmonthField.text != "" && BirthdayField.text != "" && PasswordCKField.text != ""){
                if (self.isValidEmail(testStr: eMailField.text!) == false){
                    print("信箱格式錯誤");
                    let alertcontroller = UIAlertController(title: "Error", message: "The mailbox is malformed", preferredStyle: .alert);
                    let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil);
                    alertcontroller.addAction(alertAction)
                    self.present(alertcontroller, animated: true, completion: nil)
                }else{
                    if(PasswordCKField.text == PasswordField.text){
//                        print(PasswordField.text?.characters.count)
                        if((PasswordField.text?.characters.count)! < 6 || (PasswordField.text?.characters.count)! > 12){
                            let alertcontroller = UIAlertController(title: "Error", message: "The character should be between 6 and 12", preferredStyle: .alert);
                            let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil);
                            alertcontroller.addAction(alertAction)
                            self.present(alertcontroller, animated: true, completion: nil)
                            print("密碼未介於6~12之間")
                        }else{
                            //註冊成功
                            print("註冊")
                        }
                       
                    }else{
                        let alertcontroller = UIAlertController(title: "Error", message: "The passwords do not match", preferredStyle: .alert);
                        let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil);
                        alertcontroller.addAction(alertAction)
                        self.present(alertcontroller, animated: true, completion: nil)
                    }
                    
                }
            }else{
                if(eMailField.text == ""){
                    eMailField.attributedPlaceholder = NSAttributedString(string: "Please enter email", attributes: [NSForegroundColorAttributeName: UIColor.red]);
                }
                if(PasswordField.text == ""){
                    PasswordField.attributedPlaceholder = NSAttributedString(string: "Please enter password", attributes: [NSForegroundColorAttributeName: UIColor.red]);
                }
                if(PasswordCKField.text == ""){
                    PasswordCKField.attributedPlaceholder = NSAttributedString(string: "Please enter password confirm", attributes: [NSForegroundColorAttributeName: UIColor.red]);
                }
                if(NicknameField.text == ""){
                    NicknameField.attributedPlaceholder = NSAttributedString(string: "Please enter nickname", attributes: [NSForegroundColorAttributeName: UIColor.red]);
                }
                if(BirthyearField.text == "" || BirthmonthField.text == "" || BirthdayField.text == ""){
                    let alertcontroller = UIAlertController(title: "Error", message: "Please enter your borthday", preferredStyle: .alert);
                    let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil);
                    alertcontroller.addAction(alertAction)
                    self.present(alertcontroller, animated: true, completion: nil)
                }
                
            }
        }else{
            let alertcontroller = UIAlertController(title: "Error", message: "Please agree membership terms", preferredStyle: .alert);
            let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil);
            alertcontroller.addAction(alertAction)
            self.present(alertcontroller, animated: true, completion: nil)
        }
    }
    // MARK: e-Mail檢查
    func isValidEmail(testStr:String) -> Bool {
        // print("validate calendar: \(testStr)")
        let stricterFilter:Bool = false;
        
        let stricterFilterString:String = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
        let laxString:String = ".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*"
        let emailRegex:String = stricterFilter ? stricterFilterString : laxString;
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with: testStr)
    }
    
    
    // MARK: TEXTField按下鍵盤return後動作
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        if(textField.isEqual(eMailField)){
            PasswordField.becomeFirstResponder()
        }else if(textField.isEqual(PasswordField)){
            PasswordCKField.becomeFirstResponder()
        }else if(textField.isEqual(PasswordCKField)){
            NicknameField.becomeFirstResponder()
        }else if(textField.isEqual(NicknameField)){
            NicknameField.resignFirstResponder()
        }
        return true;
    }
    //MARK: 鍵盤監聽動作(當用戶點view收起)
    func keyboardWasShown(){
        TopView.addGestureRecognizer(singleFingerTap);
    }
    func keyboardWasHidden(){
        TopView.removeGestureRecognizer(singleFingerTap);
    }
    func handleSingleTap(){
        //Do stuff here...
        eMailField.resignFirstResponder()
        PasswordField.resignFirstResponder()
        PasswordCKField.resignFirstResponder()
        NicknameField.resignFirstResponder()

    }

以下附上大概的介面圖剩下就交由大家自己去測試摟!!!



登入頁面(SWIFT3)

今天製作了登入頁面,登入頁面比較簡單沒有太複雜的物件。以下先呈現code

import UIKit

class LoginViewController: UIViewController,UITextViewDelegate,UITextFieldDelegate {
    
    @IBOutlet weak var TopView: UIView!
    @IBOutlet weak var PasswordField: UITextField!
    @IBOutlet weak var UserAccountField: UITextField!
    
    @IBOutlet weak var LogInBtn: UIButton!
    @IBOutlet weak var FB: UIButton!
    @IBOutlet weak var Google: UIButton!
    
    var singleFingerTap:UITapGestureRecognizer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //監聽鍵盤動作
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardWasShown), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardWasHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
        singleFingerTap = UITapGestureRecognizer.init(target: self, action: #selector(handleSingleTap));
        
        self.UserAccountField.delegate = self;
        self.PasswordField.delegate = self;
        UserAccountField.clearButtonMode = .always;
        PasswordField.clearButtonMode = .always;
        FB.layer.cornerRadius = 5;
        Google.layer.cornerRadius = 5;
        LogInBtn.layer.cornerRadius = 5;
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationController?.isNavigationBarHidden = true
    }
    
    @IBAction func LoginBtn(_ sender: UIButton) {
        
        if((UserAccountField.text != "") && (PasswordField.text != "")){
            if (self.isValidEmail(testStr: UserAccountField.text!) == false){
                print("信箱格式錯誤");
                let alertcontroller = UIAlertController(title: "Error", message: "The mailbox is malformed", preferredStyle: .alert);
                let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil);
                alertcontroller.addAction(alertAction)
                self.present(alertcontroller, animated: true, completion: nil)
            }else{
                //都有值登入
                print("登入");
                
            }
        }else{
            //帳號密碼為空時
            if(UserAccountField.text == ""){
                UserAccountField.attributedPlaceholder = NSAttributedString(string: "Please enter email", attributes: [NSForegroundColorAttributeName: UIColor.red]);
            }
            if(PasswordField.text == ""){
                PasswordField.attributedPlaceholder = NSAttributedString(string: "Please enter password", attributes: [NSForegroundColorAttributeName: UIColor.red]);
            }
        }
    }
    
    
    
    @IBAction func FBBtn(_ sender: UIButton) {
        
    }
    
    
    @IBAction func GoogleBtn(_ sender: UIButton) {
        
    }
    
    // MARK: e-Mail檢查
    func isValidEmail(testStr:String) -> Bool {
        // print("validate calendar: \(testStr)")
        let stricterFilter:Bool = false;
        
        let stricterFilterString:String = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
        let laxString:String = ".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*"
        let emailRegex:String = stricterFilter ? stricterFilterString : laxString;
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with: testStr)
    }
    
    // MARK: TEXTField按下鍵盤return後動作
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        if(textField.isEqual(UserAccountField)){
            PasswordField.becomeFirstResponder()
        }else{
            self.LoginBtn(.init(type: .custom))
        }
        return true;
    }
    //MARK: 鍵盤監聽動作(當用戶點view收起)
    func keyboardWasShown(){
        TopView.addGestureRecognizer(singleFingerTap);
    }
    func keyboardWasHidden(){
        TopView.removeGestureRecognizer(singleFingerTap);
    }
    func handleSingleTap(){
        //Do stuff here...
        UserAccountField.resignFirstResponder()
        PasswordField.resignFirstResponder()

    }


以上照著做就可以了喔!!測試圖片如下

下圖為按下login後print出來登入


下圖為判斷帳號(email)格式錯誤

希望能幫助到大家喔!!